一个圆形可点击区域
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>
效果如图
双向绑定