DIV CSS 佈局教程網

不依賴 jQuery 的純 JavaScript 圖片輪播做法
編輯:關於JavaScript     

上篇談的是自製輪播器的整體結構,這篇把重點放在「完全不用 jQuery、也不做過渡動畫」的最精簡版本,適合需要極小體積或想徹底理解原理的場合。

與眾不同的取捨

1. 不引任何函式庫。選取元素、增刪 class、讀寫樣式全部自己實作。

2. 不做滑動過渡。直接用 display 切換呈現,犧牲流暢度換取程式碼精簡。

3. 保留自動播放與手動切換。滑鼠移入數字鈕即暫停並跳頁,移出後恢復自動。

程式碼

<!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));
  },

  $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|$)'), ' ') : '';
  },

  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();
  },

  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(); };
    }
  },

  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>

如果要改成真正「不用動畫」的版本

既然目標是極簡,其實可以把 animate 整段拿掉,切換只靠 display:

function show(index){
  var imgs = document.querySelectorAll('.img-div img');
  var btns = document.querySelectorAll('.slide-btn a');
  for (var i = 0; i < imgs.length; i++) {
    imgs[i].style.display = (i === index) ? 'block' : 'none';
    btns[i].classList.toggle('hover', i === index);
  }
  current = index;
}

再搭配 setInterval 定時呼叫,二十行以內就能完成一個可用的輪播。

實務提醒

1. 位移距離要與圖片寬度一致。原程式碼在 play 中移動 500、hover 中移動 1000,兩者不一致會導致自動播放與手動點擊的呈現位置不同,建議統一改成讀取 img_div.offsetWidth。

2. 用 querySelectorAll 取代自己實作的 class 查詢。現代瀏覽器原生支援,程式碼可少一半。

3. 記得 clearInterval。單頁應用切換頁面時若未清除計時器,會殘留幽靈輪播。

4. 圖片可自行替換為專案實際素材,並建議為每張圖加上 alt 文字以符合無障礙要求。

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