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

双向绑定
本文介绍如何使用CSS、HTML和JavaScript创建圆形可点击区域。通过border-radius和cursor属性实现圆型样式,利用img标签的map和area属性定义圆形区域,最后通过JavaScript绑定事件判断点击是否在圆形区域内。

被折叠的 条评论
为什么被折叠?



