DIV CSS 佈局教程網

JS 特效詳解:圖片幻燈片切換的完整實作
編輯:關於JavaScript     
  • 序一(08/07/06):看到 alibaba 有個圖片切換效果,感覺不錯,想拿來用用。結果程式碼一大堆,看得眼花,還是自己寫吧。好在之前做過圖片滑動展示效果,這次輕鬆多了。
  • 序二(09/03/19):自從寫完 Tween 緩動之後就一直想重寫這個效果,近來有點時間,終於能動手。這次除了改用 Tween 緩動,也順手把算法整理了一遍,原理不變。

效果預覽

以下為可直接執行的完整範例:

程序說明

原理很單純:不斷改寫滑動物件的 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: true —— 是否垂直方向(初始化後不可改)
  • Auto: true —— 是否自動播放
  • Change: 0 —— 位移量,為 0 時自動推算
  • Duration: 50 —— 滑動持續時間
  • Time: 10 —— 滑動延時
  • Pause: 2000 —— 停頓時間(Auto 為 true 時有效)
  • onStart: function(){} —— 開始轉換時執行
  • onFinish: function(){} —— 完成轉換時執行
  • Tween: Tween.Quart.easeOut —— 緩動算子

其中 Vertical 一旦初始化就不能改;Tween 算子可從緩動效果中任選一種(範例裡用了 Quart、Back、Bounce 三種)。

另外提供的方法:

  • Next:切換下一個
  • Previous:切換上一個
  • Stop:停止自動切換
  • Run:開始或跳至指定索引

程序代碼

核心組件程式碼(依賴 $、Extend、CurrentStyle、Bind 與 Tween 這幾個輔助物件):

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved