定时器的应用—JS学习笔记2015-6-21(第62天)
定时器的管理;
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> #div1 { width:100px; height:100px; background:red; position:absolute; top:50px; left:30px; } </style> </head> <body> <input id="btn1" type="button" value="往后" /> <input id="btn2" type="button" value="往前" /> <div id="div1"></div> <script> var oBtn1 = document.getElementById('btn1'); var oBtn2 = document.getElementById('btn2'); var oDiv = document.getElementById('div1'); oBtn1.onclick = function () { clearInterval( oDiv.timer ); oDiv.timer = setInterval(function () { var speed = parseInt(getStyle( oDiv, 'left' )) + -12; // 步长 if ( speed < 10 ) { speed = 10; } oDiv.style.left = speed + 'px'; if ( speed == 10 ) { clearInterval( oDiv.timer ); } }, 30); }; oBtn2.onclick = function () { clearInterval( oDiv.timer ); oDiv.timer = setInterval(function () { var speed = parseInt(getStyle( oDiv, 'left' )) + 12; // 步长 if ( speed > 800 ) { speed = 800; } oDiv.style.left = speed + 'px'; if ( speed == 800 ) { clearInterval( oDiv.timer ); } }, 30); }; function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; } </script> </body> </html>