鼠标事件-跟随鼠标移动

案例分析:

1.鼠标不断移动,使用鼠标移动事件 mousemove;

2.在页面中不断移动,给document注册事件;

3.图片要移动距离,而且不占位置,我们使用绝对定位;

4.核心原理:每次鼠标移动,都会获得最新的鼠标坐标,把这个xy坐标作为图片的left和top值就可以移动图片。

效果:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>跟随鼠标的天使</title>
 6         <style>
 7             img{
 8                 width: 100px;
 9                 position: absolute;
10             }
11         </style>
12     </head>
13     <body>
14         <img src="图片/pic.gif" alt="">
15         <script>
16             var pic = document.querySelector('img');
17             document.addEventListener('mousemove',function(e){
18                 //1.mousemove只要我们鼠标移动1px 就会触发这个事件
19                 //2.核心原理:每次移动鼠标,我们都会得到最新的鼠标坐标,把这个x和y坐标作为图片的left和top值就可以移动图片
20                 var x = e.pageX;
21                 var y = e.pageY;
22                 //默认的元素贴着左上角对齐,让图片往上走/往左走图片的一半
23                 pic.style.left = x - 50 + 'px';   //切记 给left和top添加px单位
24                 pic.style.top = y -60 + 'px';
25             })
26         </script>
27     </body>
28 </html>

 

猜你喜欢

转载自www.cnblogs.com/cy1227/p/12896147.html