<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box">
</div>
</body>
</html>
<style>
.box{
width: 200px;
height: 200px;
background-color: blue;
margin: 20px 0 0 20px;
}
</style>
<script>
var box = document.querySelector('.box')
console.log(box);
box.addEventListener('mousemove',function(e){
var x = e.pageX - box.offsetLeft //用鼠标距离页面的距离减去盒子距离页面的距离得出鼠标在盒子内距离盒子的距离
var y = e.pageY - box.offsetTop
console.log("鼠标在盒子内的x坐标为" + x);
console.log("鼠标在盒子内的y坐标为" + y);
})
</script>
获取鼠标在盒子内的坐标
最新推荐文章于 2024-03-05 11:29:23 发布
这篇博客介绍了一个简单的HTML和JavaScript示例,通过监听鼠标move事件,实时获取并打印鼠标在蓝色方块内的x和y坐标。代码中,首先设置了一个200px*200px的蓝色div,然后使用JavaScript选择该元素并添加事件监听器,当鼠标在div内移动时,计算并输出相对于div的坐标值。
2983

被折叠的 条评论
为什么被折叠?



