DIV CSS 佈局教程網

JavaScript 圖片輪播實作:自製輕量輪播器
編輯:關於JavaScript     

輪播圖大概是首頁必備的元素。與其直接搬一個笨重的外掛,不如自己寫一個:需要的功能其實只有自動播放、滑鼠移入暫停、點擊數字直接跳頁,加上一點緩動效果而已。這份實作把 DOM 操作、樣式切換與緩動函數各自封裝,全部程式碼約百餘行。

結構設計

HTML 很單純:一個包裹層 #slide,裡面是放圖的 .img-div 與放數字按鈕的 .slide-btn。所有圖片以 CSS 隱藏,由 JS 控制顯示。

JS 部分以 zBase 物件統一管理,包含:id/標籤/class 選擇器、class 增刪、樣式讀寫、緩動函數,以及 init / animate / hover / play 四個主要方法。

完整程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>圖片輪播</title>
<style>
  .img-div img{ display:none; }
</style>
</head>
<body>
<div class="slide" id="slide">
  <div class="img-div">
    <img src="model.jpg" />
    <img src="model2.jpg" />
    <img src="model.jpg" />
    <img src="model2.jpg" />
    <img src="model.jpg" />
  </div>
  <div class="slide-btn">
    <a href="#" class="hover">1</a>
    <a href="#" class="hover">2</a>
    <a href="#" class="hover">3</a>
    <a href="#" class="hover">4</a>
    <a href="#" class="hover">5</a>
  </div>
</div>

<script type="text/javascript">
var zBase = {

  /* ---------- 基礎工具 ---------- */
  $id: function(id){ return document.getElementById(id); },

  $tagName: function(tagName, obj){
    return ((obj ? obj : document).getElementsByTagName(tagName));
  },

  // 依 class 名稱取得元素集合
  $c: function(clsN, obj) {
    var tag = this.$tagName('*', obj),
        reg = new RegExp('(^|\\s)' + clsN + '(\\s|$)'),
        arr = [];
    for (var i = 0; i < tag.length; i++) {
      if (reg.test(tag[i].className)) { arr.push(tag[i]); }
    }
    return arr;
  },

  $add: function(obj, clsN) {
    var reg = new RegExp('(^|\\s)' + clsN + '(\\s|$)');
    if (!reg.test(obj.className)) { obj.className += ' ' + clsN; }
  },

  $remove: function(obj, clsN) {
    var cla = obj.className;
    obj.className = cla ? cla.replace(new RegExp('(^|\\s)' + clsN + '(\\s|$)'), ' ') : '';
  },

  // 讀寫樣式:傳入 value 則設定,否則回傳 computed style
  css: function(obj, attr, value) {
    if (value) {
      obj.style[attr] = value;
    } else {
      return typeof window.getComputedStyle != "undefined"
        ? window.getComputedStyle(obj, null)[attr]
        : obj.currentStyle[attr];
    }
  },

  /* ---------- 緩動函數 ---------- */
  easing: {
    liner: function(t, b, c, d){ return c * t / d + b; },
    easeOut: function(t, b, c, d){ return -c * ((t = t / d - 1) * t * t * t - 1) + b; }
  },

  /* ---------- 設定 ---------- */
  config: {
    index: 0,        // 目前顯示的索引
    auto: true,      // 是否自動播放
    direct: 'left'   // 滑動方向
  },

  init: function() {
    this.slide     = this.$id('slide');
    this.img_div   = this.$c('img-div')[0];
    this.slide_btn = this.$tagName('a', this.$c('slide-btn')[0]);
    this.img_arr   = this.$tagName('img', this.img_div);
    if (this.config.auto) { this.play(); }
    this.hover();
  },

  // 以 1 秒為 duration 做位移動畫
  animate: function(obj, attr, val) {
    var d = 1000;
    if (obj[attr + "timer"]) { clearInterval(obj[attr + "timer"]); }

    var start = parseInt(zBase.css(obj, attr)),
        space = val - start,
        st    = new Date().getTime(),
        m     = space > 0 ? 'ceil' : 'floor';

    obj[attr + 'timer'] = setInterval(function(){
      var t = new Date().getTime() - st;
      if (t < d) {
        zBase.css(obj, attr, Math[m](zBase.easing["easeOut"](t, start, space, d)) + "px");
      } else {
        clearInterval(obj[attr + 'timer']);
        zBase.css(obj, attr, (start + space) + "px");
      }
    }, 20);
  },

  // 滑鼠移入數字按鈕:停掉自動播放並跳到該頁
  hover: function() {
    for (var i = 0; i < this.slide_btn.length; i++) {
      this.slide_btn[i].index = i;
      this.slide_btn[i].onmouseover = function() {
        if (zBase.slide.timer) { clearInterval(zBase.slide.timer); }
        zBase.config.index = this.index;
        for (var j = 0; j < zBase.slide_btn.length; j++) {
          zBase.$remove(zBase.slide_btn[j], 'hover');
        }
        zBase.$add(zBase.slide_btn[zBase.config.index], 'hover');
        zBase.animate(zBase.img_div, zBase.config.direct, -zBase.config.index * 1000);
      };
      this.slide_btn[i].onmouseout = function() { zBase.play(); };
    }
  },

  // 自動播放:每 3 秒切換一次
  play: function(){
    this.slide.timer = setInterval(function(){
      var tags = zBase.$tagName('img', zBase.img_div);
      for (var i = 0; i < tags.length; i++) {
        tags[i].style.display = (zBase.config.index == i) ? "block" : "none";
      }
      zBase.config.index++;
      if (zBase.config.index >= zBase.img_arr.length) { zBase.config.index = 0; }
      zBase.animate(zBase.img_div, zBase.config.direct, -zBase.config.index * 500);
      for (var j = 0; j < zBase.slide_btn.length; j++) {
        zBase.$remove(zBase.slide_btn[j], 'hover');
      }
      zBase.$add(zBase.slide_btn[zBase.config.index], 'hover');
    }, 3000);
  }
};

zBase.init();
</script>
</body>
</html>

這份程式碼裡值得注意的地方

1. animate 用時間差而非累加步長。每次都以「起始值 + 緩動(已耗時間)」重新計算位置,因此即使中途被打斷重新呼叫,也不會出現位置跳動或殘留位移。

2. direction 決定位移軸向。把 direct 抽成設定項,改成 top 就能變成上下輪播,不必改動主體邏輯。

3. hover 與 play 共用同一組切換程式碼。兩處都在做「更新索引 → 切換 display → 移動 → 同步按鈕樣式」,日後若要加入淡入淡出,只要改一處。

4. 原版本在 animate 結束時誤用了未定義的 top 變數,這裡已修正為 start + space;另外 play 中位移量 500 與 hover 中的 1000 不一致,實務上應統一為單張圖的實際寬度,否則會出現滑動距離對不上的情形。

5. 若要接真實專案,建議再補上:圖片寬度改為動態讀取 img_div.offsetWidth、加上左右箭頭、以及滑鼠移入圖片區(而非按鈕)時也暫停播放。

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