计算鼠标在盒子内的坐标
Tutorial: DOM实战
Category: JS
Published: 2026-04-07 13:58:26
Views: 20
Likes: 0
Comments: 0
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector(".box");
box.addEventListener("mousemove", function (e) {
console.log(e.pageX);
console.log(e.pageY);
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
this.innerHTML = "x坐标是" + x + " y坐标是" + y;
});
</script>
</body>
</html>