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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM