原生js写小球向右移动移动一定距离停止运动及小球加速运动
生活随笔
收集整理的這篇文章主要介紹了
原生js写小球向右移动移动一定距离停止运动及小球加速运动
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這段代碼中? 方法一:用的setInterval( )定時器 作小球移動 ? ,? 若再次點擊按鈕小球移動速度會比上一次快;
????????????????????? 方法二:用的setInterTimeout() 再次點擊按鈕? ,若要讓他保持原來的速度需要在setTimeout()定時器上方清除這個定時器,以防再次點擊帶來影響。
?????????????????????? 方法三:小球加速運動
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">#box{width: 100px;height: 100px;border-radius: 50%;background: skyblue;position: absolute;left: 0;top: 100px;}#wall{width: 2px;height:500px;position: absolute;left: 500px;background: #000;}</style> </head> <body><button id="btn">開始</button><div id="box"></div><div id="wall"></div><script type="text/javascript">//方法一var o=document.getElementById("box");var speed=2;//小球移動距離var c; //定義一個變量用來盛放定時器//點擊開始按鈕小球開始移動document.getElementById('btn').onclick=function(){move(); }//小球移動function move(){var m=getComputedStyle(o,null).left;m=parseInt(m);o.style.left=m+speed+"px";clearTimeout(c);//再次點擊按鈕小球的速度不會加快if (m>=400) {clearTimeout(c);}else{c=setTimeout(move,10);}}/*//方法二//多次點擊按鈕小球速度會加快var o=document.getElementById("box");var speed=2;//小球移動距離var c; //定義一個變量用來盛放定時器//點擊開始按鈕小球開始移動document.getElementById('btn').onclick=function(){// clearInterval(c);//多個按鈕多個方向多個定時器時需要清除定時器帶來的影響var c=setInterval(move2,10)}//小球移動2function move2(){var m=window.getComputedStyle(o,null).left;m=parseInt(m);if (m>=400) {clearInterval(c);}else{o.style.left=m+speed+"px";}}*//*//方法三 小球加速運動var o=document.getElementById("box");var speed=2;//小球移動距離var c; //定義一個變量用來盛放定時器//點擊開始按鈕小球開始移動document.getElementById('btn').onclick=function(){setInterval(move,50); }function move(){//獲取小球左邊距離var m=window.getComputedStyle(o,null).left;m=parseInt(m);// if (m>=400) {// clearInterval(c);// }else{//給小球左邊賦予新值o.style.left=m+speed+"px";// }setTimeout(move,500)}*/</script> </body> </html>?
總結
以上是生活随笔為你收集整理的原生js写小球向右移动移动一定距离停止运动及小球加速运动的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 采用python解决实际问题_Pytho
- 下一篇: mysql漏洞包_MySQL npm包中