本文實例為大家分享了setTimeout實現輪循動畫的具體代碼,供大家參考,具體內容如下
代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title></head><body> <div id='box'></div> <script> var oBox = document.getElementById("box"); var maxLeft = utils.win('clientWidth')-oBox.offsetWidth; var step = 5; var timer = null; //使用遞歸思想完成setTimeout的輪循動畫:每一次在執行動畫之前把上一次設置沒用的定時器清除掉,節約我們的內存空間 function move(){ window.clearTimeout(timer); var curLeft = utils.css(oBox,"left"); if(curLeft+step >= maxLeft){//邊界判斷 utils.css(oBox,"left",maxLeft); return; } curLeft+=step; utils.css(oBox,"left",curLeft); timer = window.setTimeout(move,10) } move(); </script></body></html>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答