JavaScript中的勻速運動和變速(緩衝)運動詳細介紹

來源:互聯網
上載者:User

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

比如勻速運動:

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

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

勻速的比如: 複製代碼 代碼如下:var timer=null;
function startMove()
{

var oDiv=document.getElementById('div1');
clearInterval(timer);
timer=setInterval(function () {
var iSpeed=1;

if(oDiv.offsetLeft>=300)
{
clearInterval(timer);
}
else
{
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
}
},30);
};

緩衝運動: 複製代碼 代碼如下:

var timer=null;
function startMove()
{
var iTarget=300;

var oDiv=document.getElementById('div1');

clearInterval(timer);
timer=setInterval(function () {
var iSpeed=(iTarget-oDiv.offsetLeft)/8;

iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);

iSpeed=Math.ceil(iSpeed);
if(oDiv.offsetLeft==iTarget)
{
clearInterval(timer);
}
else
{
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
}
document.title=oDiv.style.left+' '+iSpeed;
},30);
};

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

相關文章

聯繫我們

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