DOM事件之鼠标事件——小案例(块随鼠标移动事件)
html
1 <img id="ballImg" src="./images/ball-light-2.gif" title="彩色闪烁小球">
js:
1 var currentX = 0; 2 var currentY = 0; 3 var desX = 0; 4 var desY = 0; 5 6 window.onload = function(){ 7 var ball = document.getElementById("ballImg"); 8 9 10 11 document.addEventListener("mousemove",function(event){ 12 var e = event||window.event; 13 14 desX = e.clientX - ball.offsetWidth/2; 15 desY = e.clientY - ball.offsetHeight/2; 16 //console.log(desX+","+dexY); 17 move(ball); 18 }) 19 20 21 } 22 var timer = null; 23 function move(ball){ 24 clearInterval(timer); 25 var i = 0; 26 var speedX = (desX - currentX)/100; 27 var speedY = (desY - currentY)/100; 28 timer = setInterval(function(){ 29 // console.log(desX+","+dexY); 30 currentX = currentX + speedX 31 currentY = currentY + speedY 32 ball.style.left = currentX+ "px"; 33 ball.style.top = currentY + "px"; 34 i++; 35 36 console.log(i) 37 if(i == 100){ 38 ball.style.left = desX+ "px"; 39 ball.style.top = desY + "px"; 40 clearInterval(timer); 41 } 42 },1) 43 }
效果展示:(PS懒得加边界了哈哈哈哈哈哈就凑合着看?)
以上内容,如有错误请指出,不甚感激。
时间: 2024-10-14 04:26:24