DIV CSS 佈局教程網

jQuery + CSS 手寫一個簡潔的圖片輪播
編輯:JQuery入門技巧     

項目裡需要一個圖片輪播,網上找了一圈插件,要麼功能堆得太多,要麼定制起來別扭,最後決定自己寫一個。功能不複雜,順手留個記錄。

先說明幾個前提:整個容器不會根據圖片尺寸自動伸縮,示例用的是 1170×500 的圖,換尺寸時改一下 .pic-list 下 img 的寬度即可;.pic-list 的寬度代表整個橫幅的總寬,圖片數量多時要保證它大於「數量 × 單張寬度」。

HTML 結構

<div class="banner">
  <!--
    首尾各放一張重複圖片,用於拼接循環。
    首圖是最後一張的複製,末圖是第一張的複製。
    因此初始顯示的「第一屏」其實是 DOM 中的第二張圖,
    寬度 1170px,所以初始 left 為 -1170px。
  -->
  <div class="pic-list" style="left: -1170px">
    <img src="/static/img/4.jpg" alt="">
    <img src="/static/img/1.jpg" alt="">
    <img src="/static/img/2.jpg" alt="">
    <img src="/static/img/3.jpg" alt="">
    <img src="/static/img/4.jpg" alt="">
    <img src="/static/img/1.jpg" alt="">
  </div>

  <div id="buttons">
    <!-- span 數量與實際輪播圖數量一致,不含首尾的輔助圖 -->
    <span class="on"></span>
    <span></span>
    <span></span>
    <span></span>
  </div>

  <a href="javascript:;" class="arrow" id="prev"><</a>
  <a href="javascript:;" class="arrow" id="next">></a>
</div>

首尾複製圖是無限循環的關鍵:向左滑到頭時,畫面已經停在「複製的第一張」上,此時把 left 瞬間重置到對應的真實位置,視覺上毫無跳變。

CSS

.banner {
  width: 100%;
  height: 500px;
  overflow: hidden;
  position: relative;
}

.banner a {
  text-decoration: none;
}

.banner .pic-list {
  width: 10000px;      /* 足夠寬,容納所有橫向排列的圖片 */
  height: 500px;
  position: absolute;
  z-index: 1;
}

.banner .pic-list img {
  width: 1170px;
  float: left;
}

#buttons {
  position: absolute;
  z-index: 2;
  height: 10px;
  bottom: 20px;
  left: 550px;
}

#buttons span {
  cursor: pointer;
  float: left;
  border: 1px solid #fff;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #333;
  margin-right: 5px;
}

#buttons .on {
  background: orange;
}

.arrow {
  cursor: pointer;
  line-height: 36px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  width: 40px;
  height: 40px;
  position: absolute;
  z-index: 2;
  top: 200px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  display: none;
}

.banner:hover .arrow {
  display: block;
}

#prev { left: 20px; }
#next { right: 20px; }

JavaScript

$(document).ready(function () {
  var picNum = 4;      // 圖片數量,按實際修改
  var picWidth = 1170; // 單張圖寬度,按實際修改
  var picMaxWidth = -1 * picNum * picWidth;

  var currentPic = 1;
  var next = $('#next');
  var prev = $('#prev');
  var flag = false;    // 鎖,防止動畫未結束時重複觸發

  prev.on('click', function () {
    if (!flag) {
      calPx(1170);
      currentPic--;
      if (currentPic < 1) {
        currentPic = picNum;
      }
      $('#buttons span').eq(currentPic - 1).addClass('on').siblings().removeClass('on');
    }
  });

  next.on('click', function () {
    if (!flag) {
      calPx(-1170);
      currentPic++;
      if (currentPic > picNum) {
        currentPic = 1;
      }
      $('#buttons span').eq(currentPic - 1).addClass('on').siblings().removeClass('on');
    }
  });

  $('.banner').on('mouseover', function () {
    stop();
  }).on('mouseout', function () {
    play();
  });

  function nextClick() {
    next.click();
  }

  function play() {
    setInt = setInterval(nextClick, 2000);
  }

  function stop() {
    clearInterval(setInt);
  }

  // 手寫緩動:按固定間隔逐步移動,到目標位置後處理首尾拼接
  function calPx(leftPx) {
    flag = true;

    var left = parseInt($('.pic-list').css('left'));
    var newLeft = left + leftPx;
    var time = 300;
    var interval = 10;
    var speed = leftPx / (time / interval);

    function go() {
      var left = parseInt($('.pic-list').css('left'));

      if ((speed < 0 && left > newLeft) || (speed > 0 && left < newLeft)) {
        $('.pic-list').css('left', (left + speed) + 'px');
        setTimeout(go, interval);
      } else {
        flag = false;
        // 到達頭尾輔助圖時,瞬間跳回真實位置
        if (newLeft > -1170) {
          newLeft = picMaxWidth;
        } else if (newLeft < picMaxWidth) {
          newLeft = -1170;
        }
        $('.pic-list').css('left', newLeft + 'px');
      }
    }

    go();
  }

  play();
});

幾點值得改進的地方

  • 用 animate 或 CSS transition 替代手寫緩動。上面 calPx 裡用 setTimeout 逐步改 left 的方式,代碼量和性能都不如 $('.pic-list').animate({ left: newLeft }, 300, callback),或者乾脆用 CSS transition 交給 GPU 合成。
  • 1170 這個數字重複出現多次。既然已經聲明了 picWidth,calPx 調用處也應該用它,避免改尺寸時漏改。
  • flag 鎖要在重置位置之後再放開。目前是在動畫結束時就置 false,此時位置重置尚未完成,理論上存在極短時間內被再次點擊的窗口。
  • 索引按鈕沒有綁定點擊。目前 span 只是狀態指示,加上跳轉能力會更完整。
  • setInt 未用 var 聲明,會洩漏成全局變量。

整體思路值得借鑑的部分是首尾複製圖的處理——它讓「無限循環」不必依賴任何插件,只靠一次位置重置就完成了。剩下的都是可以在真實項目中逐步替換成更好方案的細節。

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