第一种情况
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #div1 {width:200px;height:200px;background: red;position:absolute;top:50px;} </style> <script type="text/javascript"> var timer=""; function startMove(){ var oDiv=document.getElementById('div1'); var oBtn=document.getElementById('btn1'); var speed=10; clearInterval(timer); timer=setInterval(function(){ oDiv.style.left=oDiv.offsetLeft+speed+"px" },30) } </script> </head> <body> <input type="button" id="btn1" onclick="startMove()" > <div id="div1"></div> </body> </html>
该情况下div可正常右移!
第二种情况
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #div1 {width:200px;height:200px;background: red;position:absolute;top:50px;} </style> <script type="text/javascript"> function startMove(){ var oDiv=document.getElementById('div1'); var oBtn=document.getElementById('btn1'); var speed=10; var timer=""; clearInterval(timer); timer=setInterval(function(){ oDiv.style.left=oDiv.offsetLeft+speed+"px" },30) } </script> </head> <body> <input type="button" id="btn1" onclick="startMove()" > <div id="div1"></div> </body> </html>
此情况下点击buttn次数越多 div速度越快,, 请问为什么?? timer在里面在外面有区别吗?
第三种情况
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #div1 {width:200px;height:200px;background: red;position:absolute;top:50px;} </style> <script type="text/javascript"> var oDiv=document.getElementById('div1'); var oBtn=document.getElementById('btn1'); var speed=10; var timer=""; function startMove(){ clearInterval(timer); timer=setInterval(function(){ oDiv.style.left=oDiv.offsetLeft+speed+"px" },30) } </script> </head> <body> <input type="button" id="btn1" onclick="startMove()" > <div id="div1"></div> </body> </html>
在这种情况下会报错,,但是为什么。。我定义的那些odiv obtn之类的不是全局变量吗?为什么会报错??
求高人解答!!!
堂堂堂堂糖糖糖童鞋