demo代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鼠标在盒子中的坐标</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
div {
width: 400px;
height: 400px;
font-size: 20px;
margin: 100px auto;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="box">
鼠标在盒子中的X坐标:<span></span> <br>
鼠标在盒子中的Y坐标:<span></span> <br>
</div>
<script type="text/javascript">
var box = document.getElementById("box");
var sp1 = document.getElementsByTagName("span")[0];
var sp2 = document.getElementsByTagName("span")[1];
document.onclick = function(event){
console.log(box.offsetTop,box.offsetLeft)
console.log(event.clientX,event.clientY)
var txt1 = event.clientY - box.offsetTop;
var txt2 = event.clientX - box.offsetLeft;
// console.log(txt1,txt2)
sp1.innerHTML = txt1;
sp2.innerHTML = txt2;
}
</script>
</body>
</html>