题目:获取鼠标在盒子内的坐标
进阶知识:
分析:
- 我们在盒子内点击,想要获得鼠标距离盒子左右的距离
- 首先我们得到鼠标在页面中的坐标(e.pageX,e.pageY)
- 其次得到盒子在页面中的距离(box.offsetLeft,box.offsetTop)
- 用鼠标距离页面的坐标减去盒子在页面的距离,得到鼠标在盒子内的坐标
- 如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动事件 mousemove
效果:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取鼠标在盒子内的坐标</title>
<style>
.box {
margin: 100px;
background-color: pink;
width: 200px;
height: 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>