DIV CSS 佈局教程網

JavaScript 圖片滑動切換效果實作詳解
編輯:關於JavaScript     

圖片輪播幾乎是每個門戶網站的標配。本文從最精簡的點擊切換寫法出發,再逐步升級到帶緩動函式、自動播放與滑動停頓的完整版本。

入門版:五張圖的點擊切換


這段程式把「切換控制」的思路講清楚了:用一個索引變數搭配圖片陣列,每次點擊推進索引並更新 src。這個骨架可以用在各種場景,只是還缺少滑動動畫與自動播放。

進階版:支援滑動、緩動與自動輪播

以下實作把常用工具函式、緩動演算法與輪播控制器拆成獨立區塊,方便日後替換與擴充:

var $$ = function (id) {
  return "string" == typeof id ? document.getElementById(id) : id;
};

var Extend = function (destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
};

var CurrentStyle = function (element) {
  return element.currentStyle || document.defaultView.getComputedStyle(element, null);
};

var Bind = function (object, fun) {
  var args = Array.prototype.slice.call(arguments).slice(2);
  return function () {
    return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
  };
};

var forEach = function (array, callback, thisObject) {
  if (array.forEach) {
    array.forEach(callback, thisObject);
  } else {
    for (var i = 0, len = array.length; i < len; i++) {
      callback.call(thisObject, array[i], i, array);
    }
  }
};

var Tween = {
  Quart: {
    easeOut: function (t, b, c, d) {
      return -c * ((t = t / d - 1) * t * t * t - 1) + b;
    }
  },
  Back: {
    easeOut: function (t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
    }
  },
  Bounce: {
    easeOut: function (t, b, c, d) {
      if ((t /= d) < (1 / 2.75)) {
        return c * (7.5625 * t * t) + b;
      } else if (t < (2 / 2.75)) {
        return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
      } else if (t < (2.5 / 2.75)) {
        return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
      } else {
        return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
      }
    }
  }
};

// container: 容器物件  slider: 滑動物件  count: 切換數量
var SlideTrans = function (container, slider, count, options) {
  this._slider = (slider);
  this.container = (container);
  this._timer = null;   // 定時器
  this._count = Math.abs(count); // 切換數量
  this._target = 0;     // 目標值
  this._t = this._b = this._c = 0; // tween 參數
  this.Index = 0;       // 當前索引
  this.SetOptions(options);
  this.Auto = !!this.options.Auto;
  this.Duration = Math.abs(this.options.Duration);
  this.Time = Math.abs(this.options.Time);
  this.Pause = Math.abs(this.options.Pause);
  this.Tween = this.options.Tween;
  this.onStart = this.options.onStart;
  this.onFinish = this.options.onFinish;

  var bVertical = !!this.options.Vertical;
  this._css = bVertical ? "top" : "left"; // 方向

  // 樣式設定
  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";
  this.Change = this.options.Change ? this.options.Change :
    this._slider[bVertical ? "offsetHeight" : "offsetWidth"] / this._count;
};

SlideTrans.prototype = {
  // 設定預設屬性
  SetOptions: function (options) {
    this.options = { // 預設值
      Vertical: true,   // 是否垂直方向
      Auto: true,       // 是否自動播放
      Change: 0,        // 移動量
      Duration: 30,     // 滑動持續時間
      Time: 10,         // 滑動延時
      Pause: 3000,      // 停頓時間(Auto 為 true 時有效)
      onStart: function () {},  // 開始轉換時執行
      onFinish: function () {}, // 完成轉換時執行
      Tween: Tween.Quart.easeOut // tween 運算函式
    };
    Extend(this.options, options || {});
  },

  // 開始切換
  Run: function (index) {
    index == undefined && (index = this.Index);
    index < 0 && (index = this._count - 1) || index >= this._count && (index = 0);

    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;
    this.onStart();
    this.Move();
  },

  // 移動
  Move: function () {
    clearTimeout(this._timer);
    // 未到達目標則繼續移動,否則安排下一次滑動
    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));
    }
  },

  // 移動到指定位置
  MoveTo: function (i) {
    this._slider.style[this._css] = i + "px";
  },

  // 下一張
  Next: function () {
    this.Run(++this.Index);
  },

  // 上一張
  Previous: function () {
    this.Run(--this.Index);
  },

  // 停止
  Stop: function () {
    clearTimeout(this._timer);
    this.MoveTo(this._target);
  }
};

使用時只需建立 SlideTrans 物件並傳入容器、滑動層與張數即可,例如 new SlideTrans('container', 'slider', 5, {Auto: true, Pause: 3000}),再視需要呼叫 Next()、Previous() 或 Stop()。

這個版本的價值在於分層:緩動函式(Tween)負責「怎麼動」,控制器(SlideTrans)負責「動到哪裡、何時動」,兩者互不干擾,替換動效時不必改動主邏輯。

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