javascript定时器的简单应用示例【控制方块移动】
longzhoufeng 人气:0本文实例讲述了javascript定时器的简单应用。分享给大家供大家参考,具体如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.qb5200.com 定时器的应用</title> <style> #Div1 { width: 100px; height: 100px; position: absolute; background-color: red; top: 50px; } </style> </head> <body> <input id="oBtn1" type="button" value="铵钮"> <div id="Div1"></div> <script> var oBtn = document.getElementById("oBtn1"); var oDiv = document.getElementById("Div1"); //var timer=null; //oDiv.timer=null; oBtn.onclick = function() { clearInterval(oDiv.timer) oDiv.timer = setInterval(function() { var speed = parseInt(getStyle(oDiv, "left")) + 9; if(speed > 800) { speed = 800; } oDiv.style.left = speed + "px" if(speed == 800) { clearInterval(oDiv.timer); //alert(speed) } }, 50) } function getStyle(obj, attr) { return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr] } </script> </body> </html>
运行结果:
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容