码迷,mamicode.com
首页 > 移动开发 > 详细

JS_DOM之小球随鼠标移动事件

时间:2016-09-19 11:40:12      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

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懒得加边界了哈哈哈哈哈哈就凑合着看?)

 

 

 

 

以上内容,如有错误请指出,不甚感激。

JS_DOM之小球随鼠标移动事件

标签:

原文地址:http://www.cnblogs.com/adelina-blog/p/5884388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!