天天看點

玩具一

一個圓形可點選區域

CSS解法

使用

border-radius

渲染圓型區域,并添加

cursor:pointer

屬性

<div id="circle"></div>
  .circle {
    background-color: pink;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    cursor: pointer;
  }
           

HTML解法

利用

img

标簽的

map

area

來實作

  • img

    标簽中的

    usemap

    需要與

    area

    中的

    name

    id

    相對應。
  • area

    标簽中的

    shape

    決定形狀,

    shape:circle

    表示圓形,

    coords

    也就代表圓形的圓心坐标和半徑。
<img src="./pic.jpg" usemap="#circle" alt="" width="300px" height="200px">
    <map name="circle" id="circle">
      <area shape="circle" coords="150,100,100" href="https://www.w3school.com.cn/tags/tag_map.asp" target="_blank" alt="">
    </map>
           

綁定JS事件

  • e = e||window.event

    ,為了相容IE浏覽器中的事件。
  • e.offsetX

    表示區域内的偏移量。
<div style="border: 1px solid yellow;display: inline-block;" id="square">
    <div class="circle" id="circle"></div>
  </div>
<script>
  let pointer = document.getElementById("square")
  function foo(target, callback) {
    target.onclick = function (e) {
      e = e || window.event
      let x0 = 50,
        y0 = 50
      let x = e.offsetX,
        y = e.offsetY
      let len = Math.abs(Math.sqrt(Math.pow((x - x0), 2) + Math.pow((y - y0), 2)))
      if (len <= 50) callback()
      else {
        alert("外界區域")
      }
    }
  }
  foo(pointer, function () {
    alert("進入圓型點選區域")
  })
</script>
<style>
  .circle {
    background-color: pink;
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
</style>
           

效果如圖

玩具一

雙向綁定