JS_DOM之小球隨鼠標移動事件


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懶得加邊界了哈哈哈哈哈哈就湊合着看?)

 

以上內容,如有錯誤請指出,不甚感激。

 

 

 


免責聲明!

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



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