案例:获取鼠标在盒子内的坐标
需求: 我们在盒子内移动鼠标,想要得到鼠标距离盒子左右的距离。
案例分析:
① 我们在盒子内点击,想要得到鼠标距离盒子左右的距离。
② 首先得到鼠标在页面中的坐标(e.pageX, e.pageY)。
③ 其次得到盒子在页面中的距离 ( box.offsetLeft, box.offsetTop)。
④ 用鼠标距离页面的坐标减去盒子在页面中的距离,得到鼠标在盒子内的坐标。
⑤ 如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动事件 mousemove。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>案例:计算鼠标在盒子内的坐标</title>
<style>
.box {
width: 300px;
height: 300px;
background-color: pink;
margin: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box');
box.addEventListener('mousemove', function (e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
this.innerHTML = 'x的坐标是' + x + ' y的坐标是' + y;
});
</script>
</body>
</html>