js_元素随鼠标移动而移动(mousemove事件)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3   <head>
 4     <meta charset="UTF-8" />
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 6     <title>Document</title>
 7     <style>
 8       img {
 9         /* 位置要设置为绝对定位 */
10         position: absolute;
11       }
12     </style>
13   </head>
14   <body>
15     <img src="./img/open.png" />
16     <script>
17       var pic = document.querySelector('img')
18       // 设置鼠标移动监听事件,要以整个document为对象;
19       document.addEventListener('mousemove', function (e) {
20         // 获取页面中鼠标的x,y坐标;
21         var x = e.pageX
22         var y = e.pageY
23         // 给图片设置位置
24         pic.style.top = y - 24 + 'px'
25         pic.style.left = x - 24 + 'px'
26       })
27     </script>
28   </body>
29 </html>
时间如白驹过隙,忽然而已,且行且珍惜......
原文地址:https://www.cnblogs.com/UnfetteredMan/p/13615547.html