javascript关于运动的各种问题经典总结
本文实例总结了javascript关于运动的各种问题。分享给大家供大家参考。具体如下:
一、JS运动的各种问题
问题一:
错误代码:
?
1 2 3 4 5 6 7 8 9 10 11 function startMove(){ var timer=null; var div1=document.getElementById("div1"); if (div1.offsetLeft==300){ clearInterval(timer); }else{ timer=setInterval(function(){ div1.style.left=div1.offsetLeft+10+"px"; },30) } }希望实现的功能:
打开定时器timer,让div1运动到300px,然后让div1停下即关掉定时器。
错误之处:
if语句错误,代码首先设置一个null定时器timer,然后如果div1的左边距为300px,则关掉定时器timer。否则一直运动。但是if并不是循环语句,if语句执行一次之后将不再执行。所以永远不会关闭定时器。
正确代码:
?
1 2 3 4 5 6 7 8 9 10 var timer=null; function startMove(){ var div1=document.getElementById("div1"); timer=setInterval(function(){ if (div1.offsetLeft==300){ clearInterval(timer); } div1.style.left=div1.offsetLeft+10+"px"; },30) }问题二:
错误代码:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 function startMove(){ var speed=1; var timer=null; var oDiv1=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ if (oDiv1.offsetLeft>=300){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30) }希望实现的功能:
连续点击开始按钮,div1会加速,这是因为每当点击按钮一次,就会开启一个定时器,累积起来就会加速,所以要在开启定时器之前不管有没有定时器开启都要先关闭一次定时器。但是添加了关闭定时器的clearInterval方法之后,依然会加速。
错误之处:
将timer变量放在了startMove方法里面,相当于每点击一次按钮,就会执行一次startMove方法,生成了一个闭包,因此创建了一个局部timer,每一个闭包当中的timer并不会共享,所以还是相当于生成了点击次数的闭包timer。
正确代码:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 var timer=null; function startMove(){ var speed=1; var oDiv1=document.getElementById("div1"); clearInterval(timer); timer=setInterval(function(){ if (oDiv1.offsetLeft>=300){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30) }实现分享栏进出功能:
代码:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div1{ width: 150px; height: 200px; background: burlywood; position: absolute; left: -150px; } span{ width: 20px; height: 60px; position: absolute; background: gold; right: -20px; top: 70px; } </style> <script> window.onload=function(){ var oDiv1=document.getElementById("div1"); oDiv1.onmouseover=function(){ move(0); }; oDiv1.onmouseout=function(){ move(-150); }; }; var timer=null; function move(target){ var oDiv1=document.getElementById("div1"); var speed=0; if (oDiv1.offsetLeft<target){ speed=10; }else{ speed=-10; } clearInterval(timer); timer=setInterval(function(){ if(oDiv1.offsetLeft==target){ clearInterval(timer); }else{ oDiv1.style.left=oDiv1.offsetLeft+speed+"px"; } },30); } </script> </head> <body> <div id="div1"> <span id="span1">分享到</span> </div> </body> </html>实现图片淡入淡出功能:
代码:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53