以下為可直接執行的完整範例:
原理很單純:不斷改寫滑動物件的 left(水平切換)或 top(垂直切換),切換的動態感就出來了。
首先需要一個容器。程式會自動把容器的 overflow 設為 hidden,若它既不是 relative 也不是 absolute,則順手設成 relative;滑動物件則設為絕對定位:
var p = CurrentStyle(this._container).position;
p == "relative" || p == "absolute" || (this._container.style.position = "relative");
this._container.style.overflow = "hidden";
this._slider.style.position = "absolute";
若沒有指定 Change(每次切換的位移量),程式會依滑動物件的尺寸自動推算:
this.Change = this.options.Change ? this.options.Change :
this._slider[bVertical ? "offsetHeight" : "offsetWidth"] / this._count;
呼叫 Run 便開始切換,其中有一個可選參數用來指定要切換到的索引:
index == undefined && (index = this.Index);
index < 0 && (index = this._count - 1) || index >= this._count && (index = 0);
接著準備 tween 緩動所需的四個參數——_target(目標值)、_t(時間)、_b(初始值)、_c(變化量):
this._target = -Math.abs(this.Change) * (this.Index = index);
this._t = 0;
this._b = parseInt(CurrentStyle(this._slider)[this.options.Vertical ? "top" : "left"]);
this._c = this._target - this._b;
Duration(持續時間)則是自行定義的屬性。參數備齊後呼叫 Move 開始移動:
if (this._c && this._t < this.Duration) {
this.MoveTo(Math.round(this.Tween(this._t++, this._b, this._c, this.Duration)));
this._timer = setTimeout(Bind(this, this.Move), this.Time);
}else{
this.MoveTo(this._target);
this.Auto && (this._timer = setTimeout(Bind(this, this.Next), this.Pause));
}
判斷條件只有兩個:_c 是否有值(等於 0 代表不需要移動),以及 _t 是否已達 Duration。不滿足就繼續移動,否則直接歸位到目標值,並在 Auto 開啟時排下一輪切換。
實例化需要三個參數:容器物件、滑動物件、切換數量,之後直接呼叫 Run 即可。
new SlideTrans("idContainer", "idSlider", 3).Run();
可選屬性如下:
其中 Vertical 一旦初始化就不能改;Tween 算子可從緩動效果中任選一種(範例裡用了 Quart、Back、Bounce 三種)。
另外提供的方法:
核心組件程式碼(依賴 $、Extend、CurrentStyle、Bind 與 Tween 這幾個輔助物件):