Realization ideas:
- Click inside the box to get the distance between the mouse and the left and right of the box
- First get the coordinates of the mouse on the page
e.pageX
,e.page
- Second, get the distance of the box on the page
box.offsetLeft
,box.offsetTop
- Subtract the distance of the box in the page from the coordinates of the mouse from the page to get the coordinates of the mouse in the box
- If you want to move the mouse, get the latest coordinates and use the mouse to move
mousemove
effect:
(The mouse disappeared after the screenshot--)
Code:
<!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 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>