(39)JS運動之緩衝運動

來源:互聯網
上載者:User

標籤:style   blog   http   使用   os   width   

基本思路:使用定時器讓物體向右運動,在運動的過程中再不是勻速運動,而是先快後慢,即距離越大,速度越快,距離越小,速度越小,但是到達終點的時候,必須注意要使用向上取整函數Math.ceil()和向下取整函數Math.floor();這樣才能夠正確無誤地到達終點,而不是有出入。

<!DOCTYPE HTML><!----><html><head><meta charset="utf-8"><title></title><style>#div1{width:100px;height:100px;background:red;position:absolute;left:0px;//left:600px;top:50px;}#div2{width:1px;height:300px;background:red;position:absolute;left:300px;top:0px;background:black;}</style> <script>function startMove(){var oDiv=document.getElementById('div1');setInterval(function(){var speed=(300-oDiv.offsetLeft)/10;speed=speed>0?Math.ceil(speed):Math.floor(speed);//向上取整oDiv.style.left=oDiv.offsetLeft+speed+'px';document.title=oDiv.offsetLeft+','+speed;},30);}</script></head><body>   <input type="button" value="開始運動" onclick="startMove()"/>   <div id="div1"></div>   <div id="div2">/<div></body></html>
:

初始狀態,分別從左出發和從右出發:




沒取整導致有出入的情況,title表示終點位置和速度大小:

取整沒誤差情況:





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.