效果預覽:
運行代碼框
[ctrl+a 全部選擇 提示:你可先修改部分代碼,再按運行]
程序說明
原理就是通過不斷設置滑動對象的left(水平切換)和top(垂直切換)來實現圖片切換的動態效果。
首先需要一個容器,程序會自動設置容器overflow為hidden,如果不是相對或絕對定位會同時設置position為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);
== 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程序開始移動了。
里面很簡單,首先判斷_c是否有值(等于0表示不需要移動)和_t是否到達duration,
未滿足條件就繼續移動,否則直接移動到目標值并進行下一次切換:
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));
}
|||
使用說明
實例化需要3個參數,分別是容器對象,滑動對象和切換數量,之后可以直接執行run方法運行:
new slidetrans("idcontainer", "idslider", 3).run();
還有以下可選屬性:
其中vertical初始化后就不能修改,tween算子可參照這里的緩動效果選擇(實例中選了其中3個)。
還有提供了以下方法:
程序代碼:
代碼拷貝框
[ctrl+a 全部選擇 然后拷貝]
新聞熱點
疑難解答