2014-02-26 54 views
0

我不想花費特定的時間來完成動畫,而是希望持續時間是開始和結束值差異的函數。換句話說,遠處的動畫屬性應該改變與接近的東西相同的速度。如何控制元素屬性動畫的速率,而不是持續時間?

我已經設法通過手動更改持續時間來實現這個工作,但這並不能爲我正在實現的目標提供足夠強大的解決方案。

HTML:

<div class="container" id="wrong"> 
    <div class="top"></div> 
    <div class="middle"></div> 
</div> 

<div class="container" id="right"> 
    <div class="top"></div> 
    <div class="middle"></div> 
</div> 

CSS:

.container { position: relative; float: left; width: 100px; height: 200px; } 
.container > div { width: 50px; height: 50px; position: absolute; } 
.top { background-color: red; } 
.middle { background-color: blue; left: 50px; top: 50px; } 

JS:

var fin  = { top: '100px' }, 
    duration = 2000; 

var animate = function() { 
    $('.top').css('top', 0); 
    $('.middle').css('top', '50px'); 

    $('#wrong > div').animate(fin, duration, 'linear'); 

    $('#right .top').animate(fin, duration, 'linear'); 
    /* half the distance so use half the time */ 
    $('#right .middle').animate(fin, duration/2, 'linear'); 
}; 

animate() 
setInterval(animate, 3000); 

http://jsfiddle.net/SrQ77/

+0

當等待'animate'回調如果距離爲0,則會卡住等待無操作動畫完成 - 這是我試圖避免的。 – Wex

回答

1

速度=距離/時間

你可以安排它,以便

時間=距離/速度

並且您還希望動畫以相同的速度運行。所以,你可以忽略變速,並與剛剛

時間繼續=距離

您可以使用https://api.jquery.com/offset/來幫助你找出距離

1

你算算吧。

http://jsfiddle.net/SrQ77/1/

var fin  = 100, 
    duration = 2000; 

var animate = function() { 

    $('.top').css('top', 0); 
    $('.middle').css('top', '50px'); 
    $('#wrong .top').animate({top: fin+'px'}, ((fin - $('#wrong .top').position().top)/fin) * duration, 'linear'); 
    $('#wrong .middle').animate({top: fin+'px'}, ((fin - $('#wrong .middle').position().top)/fin) * duration, 'linear'); 

    $('#right .top').animate({top: fin+'px'}, duration, 'linear'); 
    /* half the distance! */ 
    $('#right .middle').animate({top: fin+'px'}, duration/2, 'linear'); 
}; 

animate() 
setInterval(animate, 3000); 
相關問題