我目前正在嘗試編寫自己的JavaScript庫。我正在編寫動畫回調函數,但我無法獲得精確的結束值,尤其是當動畫持續時間較短時。JavaScript:實現精確的動畫結束值?
現在,我只針對位置動畫(左,上,右,下)。當我的動畫完成後,它們最終在動畫速度更快時出現5px的誤差,動畫出現1000+ ms或更長的時間時出現0.5px〜的動畫。這是回調的大部分,以下是註釋。
var current = parseFloat(this[0].style[prop] || 0)
// If our target value is greater than the current
, gt = !!(value > current)
, delta = (Math.abs(current - value)/(duration/13)) * (gt ? 1 : -1)
, elem = this[0]
, anim = setInterval(function(){
elem.style[prop] = (current + delta) + 'px';
current = parseFloat(elem.style[prop]);
if (gt && current >= value || !gt && current <= value) clearInterval(anim);
}, 13);
this[0]
和elem
均引用目標DOM元素。
prop
引用以動畫,left
,top
,bottom
,right
等
current
是DOM元素的屬性的當前值的屬性。
value
是動畫所需的值。
duration
是動畫應該持續的指定持續時間(以毫秒爲單位)。
13
是setInterval
延遲(對於所有瀏覽器來說,這大致應該是絕對最小值)。
gt
是var
是true
如果value
超過初始current
,否則爲false
。
我該如何解決誤差?