鼠标点击跟随,鼠标点击哪里,图片跟随到哪里;
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 #image { 8 width: 99px; 9 position: absolute; 10 top:0; 11 left: 0; 12 } 13 </style> 14 </head> 15 <body> 16 <img src="img.jpg" alt="" id="image"/> 17 </body> 18 </html> 19 <script> 20 // 1.第一步获取元素; 21 // 2.建立缓动东环定时器 22 // 3.建立事件,获得target值 23 var image = document.getElementById("image"); 24 //注意这里的点击对象是document不是img 25 document.onclick = function(event) { 26 var event = event || window.event; 27 targetX = event.clientX - image.offsetWidth /2; 28 targetY = event.clientY - image.offsetHeight /2; 29 } 30 // 缓动 31 var leaderX = 0, 32 leaderY= 0, 33 targetX = 0, 34 targetY = 0; 35 setInterval(function() { 36 leaderX = leaderX + (targetX - leaderX) / 10; 37 leaderY = leaderY + (targetY - leaderY) / 10; 38 image.style.left = leaderX + "px"; 39 image.style.top = leaderY + "px"; 40 },10) 41 </script>
原理:将鼠标点击事件获得的clientX,clientY的值赋值给图片的style.left/style.top;
一辈子很短,努力的做好两件事就好;第一件事是热爱生活,好好的去爱身边的人;第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;