Claim:
- In the browser page, the picture follows the mouse in real time
- The mouse is in the center of the picture
Realization ideas:
- The mouse is constantly moving, use the mouse movement event:
mousemove
- Move in the page,
document
register for events - The picture needs to move the distance, and does not occupy the position, use absolute positioning
- Every time the mouse moves, get the latest mouse coordinates, use this
x
andy
coordinates as thetop
sum of theleft
picture to move the picture
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
/* 因为图片不能影响页面其他的布局,所以用绝对定位 */
position: absolute;
}
</style>
</head>
<body>
<img src="https://img-blog.csdnimg.cn/20201026075813798.png" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
// 获取当前鼠标到页面的距离
var x = e.pageX;
var y = e.pageY;
// 选用图片大小为50*50像素,让鼠标居中在它中间,x左移25px,y上移25px
pic.style.left = x - 25 + 'px';
pic.style.top = y - 25 + 'px';
});
</script>
</body>
</html>
Realization effect:
Copy the code into Notepad, rename it xx.html
, and save. Just use the browser to open it.