JavaScript中的所有計時器均基於本地普通舊式JavaScript函數setInterval()
或setTimeout()
。即使jQuery在內部使用它。
同步定時器的訣竅是確保只有一個調用setInterval()
,所以自己構建一些東西。
的動畫可設計有:
,每次你的函數被稱爲setInterval()
,你可以一次設置所有的DOM元素到正確的位置。要找出一個元素應該是在每個動畫幀,可以使用:
var diff = (to - from);
var stepValue = from + diff * percentage;
jQuery的緩動函數,可以直接調用,而最後陳述變成:
var stepValue = jQuery.easing[ easingMethod ](percentage, 0, from, diff);
我「已經把這個變成一個類:
/**
* Animation timeline, with a callback.
*/
function AnimationTimeline(params, onstep)
{
// Copy values.
// Required:
this.from = params.from || 0; // e.g. 0%
this.to = params.to || 1; // e.g. 100%
this.onstep = onstep || params.onstep; // pass the callback.
// Optional
this.steps = params.steps || 10;
this.duration = params.duration || 300;
this.easing = params.easing || "linear";
// Internal
this._diff = 0;
this._step = 1;
this._timer = 0;
}
jQuery.extend(AnimationTimeline.prototype, {
start: function()
{
if(this.from == this.to)
return;
if(this._timer > 0)
{
self.console && console.error("DOUBLE START!");
return;
}
var myself = this;
this._diff = (this.to - this.from);
this._timer = setInterval(function() { myself.doStep() }, this.duration/this.steps);
}
, stop: function()
{
clearInterval(this._timer);
this._timer = -1;
this._queue = [];
}
, doStep: function()
{
// jQuery version of: stepValue = from + diff * percentage;
var percentage = (this._step/this.steps);
var stepValue = jQuery.easing[ this.easing ](percentage, 0, this.from, this._diff);
// Next step
var props = { animationId: this._timer + 10
, percentage: percentage
, from: this.from, to: this.to
, step: this._step, steps: this.steps
};
if(++this._step > this.steps)
{
stepValue = this.to; // avoid rounding errors.
this.stop();
}
// Callback
if(this.onstep(stepValue, props) === false) {
this.stop();
}
}
});
現在你可以使用:
var el1 = $("#element1");
var el2 = $("#element2");
var animation = new AnimationTimeline({
easing: "swing"
, onstep: function(stepValue, animprops)
{
// This is called for every animation frame. Set the elements:
el1.css({ left: ..., top: ... });
el2.css({ left: ..., top: ... });
}
});
// And start it.
animation.start();
添加暫停/恢復是讀者的練習。
很好找!比「最佳答案」容易得多。 – grant 2011-10-15 05:13:21