JavaScript中的勻速運動和變速(緩衝)運動

來源:互聯網
上載者:User

個人網站

一個div的運動其實就是它與瀏覽器邊框的距離在變動。如果他變化的速率一定,那就是勻速運動;如果變化的速率不一定,那麼就是變速運動。當,變動率與聚離瀏覽器邊框的距離成比例的話,那麼就可以說是div在做緩衝運動。 
其實,很簡單,就是用一個定時器(timer),每隔一段時間來改變div聚瀏覽器邊框的距離。 

比如勻速運動: 

進入定時器:(每隔30ms做) 
if(是否到達終點) 
{ 停止定時器} 
else do{ 改變距離} 

改變距離的方法決定是勻速還是變速(緩衝)運動。 

勻速的比如: 

Javascript代碼  
  1. var timer=null;  
  2.   
  3. function startMove()  
  4. {  
  5.   
  6. var oDiv=document.getElementById('div1');  
  7. clearInterval(timer);  
  8. timer=setInterval(function () {  
  9. var iSpeed=1;  
  10.   
  11. if(oDiv.offsetLeft>=300)  
  12. {  
  13. clearInterval(timer);  
  14. }  
  15. else  
  16. {  
  17. oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';  
  18. }  
  19. },30);  
  20. };  

緩衝運動: 

Java代碼  
  1. var timer=null;  
  2. function startMove()  
  3. {  
  4. var iTarget=300;  
  5.   
  6. var oDiv=document.getElementById('div1');  
  7.   
  8. clearInterval(timer);  
  9. timer=setInterval(function () {  
  10. var iSpeed=(iTarget-oDiv.offsetLeft)/8;  
  11.   
  12. iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);  
  13.   
  14. iSpeed=Math.ceil(iSpeed);  
  15. if(oDiv.offsetLeft==iTarget)  
  16. {  
  17. clearInterval(timer);  
  18. }  
  19. else  
  20. {  
  21. oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';  
  22. }  
  23. document.title=oDiv.style.left+' '+iSpeed;  
  24. },30);  
  25. };  


這樣,一個運動架構就寫好了!原理很簡單,不過還有待完善。慢慢來吧!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.