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

时间:2020-09-17 13:26:10   收藏:0   阅读:72
 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>

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!