如何绘制一个圆形可点击区域
简单来讲,画一个圆,能够点击。
本文将讲述三种方法,分别从HTML
标签绘制、CSS
样式绘制以及JavaScript
事件监听绘制圆形可点击区域。
使用map
和area
标签
利用img
标签可匹配的map
和area
使用这种方法必须将img
标签的usemap
属性与map
标签的name
属性与id
属性相关联。
然后在area
标签中,设置所绘制的shape
形状与圆形的圆心和半径。
<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>
使用border-radius
搭配cursor
使用border-radius
圆角边框绘制圆形,添加cursor
属性作为可点击。
<div id="circle"></div>
.circle {
background-color: pink;
width: 100px;
height: 100px;
border-radius: 50%;
cursor: pointer;
}
绑定JavaScript
事件监听坐标
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>
猛虎分享
一起进步
共勉
2020前端最新学习资源(一)mp.weixin.qq.com![371b80bea720461de0f4215e050415c2.png](https://img-blog.csdnimg.cn/img_convert/371b80bea720461de0f4215e050415c2.png)