實作思路:
- 在盒子內點擊,想要得到滑鼠距離盒子左右的距離
- 首先得到滑鼠在頁面中的坐標
e.pageX,e.page - 其次得到盒子在頁面中的距離
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">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 300px;
height: 300px;
background-color: pink;
margin: 200px;
}
</style>
</head>
<body>
<div ></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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/168775.html
標籤:JavaScript
