js實現緩衝運動,和勻速運動有點不相同

來源:互聯網
上載者:User

標籤:

緩衝運動和勻速運動有點不同,看圖可以知道緩衝運動速度是越來越慢的。

 1 <style> 2   *{ 3     padding:0; 4     margin:10px 0; 5   } 6     #div1{ 7           height:100px; 8           width:100px; 9           background:green;10           float:left;11           position:relative;12           left:1000px;13     }14     #div2{15         border-left:1px solid black;16         position:absolute;17         height:200px;18         left:600px;19         float:left;20     }21 </style>22 23 24 <body>25 <div id="div1"></div>26 <div id="div2"></div>27 </body>

首先定義兩個div,一個div只看見一條邊,另外一個做運動

js代碼如下,帶注釋

<script>    var i=setInterval(function startMove ()    {        var div1=document.getElementById("div1");         var speed=(600-div1.offsetLeft)/30;  //首先擷取速度,因為div1。offsetleft=1000,所以此速度為負數        speed=speed>0?Math.ceil(speed):Math.floor(speed);  //將速度上下取整,像素沒有小數        div1.style.left=div1.offsetLeft+speed+‘px‘;  //因為速度為負數,所以offsetleft越來越小,向左運動               if (div1.offsetLeft==600)   //當達到div2的邊時停止運動        {          clearInterval(i);        }    }, 30)</script>

 

js實現緩衝運動,和勻速運動有點不相同

聯繫我們

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