//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!");
}); <div class="circle" onclick="alert('Clicked!')">点击我</div>
<style>
.circle {
width: 100px; /* 设置圆的宽度 */
height: 100px; /* 设置圆的高度 */
border-radius: 50%; /* 边框半径为50%创建圆形 */
cursor: pointer; /* 鼠标悬停时显示手形图标 */
}
</style> 2. svg <svg width="100" height="100">
<circle cx="50" cy="50" r="50" fill="red" cursor="pointer" onclick="alert('Clicked!')"/>
</svg> 3. js <script>
// 圆的参数
const cx = 150; // 圆心 x 坐标
const cy = 150; // 圆心 y 坐标
const r = 100; // 圆的半径
// 监听鼠标点击事件
document.addEventListener('click', function(e) {
const x = e.clientX; // 获取鼠标点击的 x 坐标
const y = e.clientY; // 获取鼠标点击的 y 坐标
// 计算点到圆心的距离
const distance = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(y - cy, 2));
// 判断距离是否等于圆的半径(这里可以设置一个小的误差范围来判断点是否在圆的边缘)
if (Math.abs(distance - r) < 1) {
console.lo***在圆上');
} else {
console.lo***不在圆上');
}
});
</script> <!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>