//css代码 #demo{ width: 400px; height: 400px; border: 1px solid black; margin: 300px auto; } //html和js <div id="demo"></div> <script> var demo = document.getElementById('demo'); demo.onclick = function(e){ //获取正方形的中心 let left = this.getBoundingClientRect().left + this.offsetWidth / 2; let top = this.getBoundingClientRect().top + this.offsetHeight / 2; //每次鼠标点击的坐标点 let x1 = e.clientX; let y1 = e.clientY; //根据两点间距离公式求出鼠标点击的位置距离圆心的距离 //有可能是负数,因此加上绝对值 let distance = Math.abs(Math.sqrt(Math.pow(x1 - left, 2) + Math.pow(y1 - top, 2))); //如果两点间距离大于规定的半径距离则不触发事件 if(distance > 100){ console.log('在这个圆内'); } } </script>
//第一种 使用image map
<img id="blue" class="click-area" src="blue.gif" usemap="#Map" />
<map name="Map" id="Map" class="click-area"> <area shape="circle" coords="50,50,50"/>
</map>
#blue{ cursor:pointer; width:100px; height:100px; }
//第二种 使用CSS border-radius <div id="red" class="click-area" ></div>
#red{ cursor:pointer; background:red; width:100px; height:100px; border-radius:50%; }
//第三种 使用js检测鼠标位置 <div id="yellow" class="click-area" ></div>
$("#yellow").on('click',function(e) { var r = 50; var x1 = $(this).offset().left+$(this).width()/2; var y1 = $(this).offset().top+$(this).height()/2; var x2= e.clientX; var y2= e.clientY; var distance = Math.abs(Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))); if (distance <= 50) alert("Yes!"); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding:0; } .circle{ width: 200px; height: 200px; border-radius: 200px; background-color: pink; cursor: pointer; } </style> </head> <body> <div class="circle"></div> <script> var div = document.querySelector(".circle"); document.addEventListener("click",function(e){ let circleX = div.offsetWidth / 2; let circleY = div.offsetHeight / 2; let clickX = e.clientX - div.offsetLeft; let clickY = e.clientY - div.offsetTop; let distance = Math.abs(Math.sqrt(Math.pow(circleX-clickX,2)+Math.pow(circleY-clickY,2))) if(distance<=100){ alert("在圆内"); }else{ alert("在圆外") } }) </script> </body> </html>