1. 程式人生 > >定時器函式的應用setInterval()

定時器函式的應用setInterval()

setInterval(function(){},time) 該函式表示每個time的時間就執行function(){} 下列列子是在js裡面實現一個div自動運動 var div=document.createElement(‘div’); //建立一個div document.body.appendChild(div); //往body新增div div.style.width=“100px”; div.style.height=“100px”; div.style.backgroundColor=“red”; div.style.position=“absolute”; div.style.top=“20px”; div.style.left=“20px”;*/ var timer=setInterval (function() { div.style.left=parseInt(div.style.left)+10+“px”; div.style.top=parseInt(div.style.top)+10+“px”; console.log(div.style.left); if(parseInt(div.style.left)>300){ clearInterval(timer); //停止定時器 } },100)