萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Banner 輪播插件開發實戰:結構、樣式、邏輯完整拆解

項目背景

90% 以上網站需要 Banner 輪播。本文分享一個輕量級 jQuery 輪播插件的完整實現:HTML 結構、CSS 關鍵樣式、JS 核心邏輯(含參數配置、自動播放、手動切換、指示器同步、無縫循環)。

HTML 結構

<div class="play_box"> <!-- 動畫容器 -->
  <div class="imgBox"> <!-- 圖片軌道 -->
    <img src="images/banner01.jpg" alt="Banner 1">
    <img src="images/banner02.jpg" alt="Banner 2">
    <img src="images/banner03.jpg" alt="Banner 3">
    <img src="images/banner04.jpg" alt="Banner 4">
  </div>
  <span class="prev" title="上一張"></span>
  <span class="next" title="下一張"></span>
  <ul class="pic_btn_list"><!-- 指示器由 JS 動態生成 --></ul>
</div>

CSS 關鍵樣式

.play_box {
  position: relative;
  width: 1002px;           /* 容器寬度 = 單圖寬度 */
  height: 300px;           /* 容器高度 */
  margin: 0 auto;
  overflow: hidden;        /* 隱藏溢出圖片 */
  font-size: 0;            /* 消除 inline-block 間隙 */
}

.imgBox {
  position: absolute;
  top: 0; left: 0;
  width: 4008px;           /* 4 張圖 × 1002px */
  height: 100%;
  font-size: 0;
  transition: left 0.5s ease; /* 平滑滑動 */
}

.imgBox img {
  display: inline-block;
  width: 1002px;
  height: 300px;
  vertical-align: top;
}

/* 切換按鈕 */
.prev, .next {
  position: absolute;
  top: 50%; transform: translateY(-50%);
  width: 40px; height: 40px;
  background: rgba(0,0,0,.3) url(arrows.png) no-repeat center;
  border-radius: 50%;
  cursor: pointer;
  opacity: 0; transition: opacity .3s;
  z-index: 10;
}
.play_box:hover .prev, .play_box:hover .next { opacity: 1; }
.prev { left: 20px; background-position: 0 0; }
.next { right: 20px; background-position: -40px 0; }

/* 指示器 */
.pic_btn_list {
  position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
  display: flex; gap: 8px; z-index: 10;
}
.pic_btn_list li {
  width: 12px; height: 12px;
  border-radius: 50%;
  background: rgba(255,255,255,.5);
  cursor: pointer;
  transition: background .3s, transform .2s;
}
.pic_btn_list li.ddd { /* 激活態 className 可配置 */
  background: #fff;
  transform: scale(1.2);
}

JS 核心邏輯(含詳細註釋)

$(document).ready(function () {
  // ========== 參數配置區 ==========
  const IMG_WIDTH   = 1002;      // 單圖寬度(根據設計稿)
  const INTERVAL    = 3000;      // 自動播放間隔 (ms)
  const ACTIVE_CLS  = 'ddd';     // 指示器激活 class
  const ANIM_DUR    = 500;       // 動畫時長 (ms)
  // ================================

  const $imgBox     = $('.imgBox');
  const $imgs       = $imgBox.find('img');
  const IMG_COUNT   = $imgs.length;
  const $playBox    = $('.play_box');
  const $prev       = $('.prev');
  const $next       = $('.next');
  const $indicators = $('.pic_btn_list');

  let currentIndex = 0;          // 當前顯示第幾張 (0-based)
  let timerId      = null;       // 自動播放定時器
  let isAnimating  = false;      // 防止連點導致動畫隊列堆疊

  // ---- 初始化指示器 ----
  function initIndicators() {
    $indicators.empty();
    for (let i = 0; i < IMG_COUNT; i++) {
      $indicators.append(`<li data-index="${i}"></li>`);
    }
    $indicators.find('li').eq(0).addClass(ACTIVE_CLS);
  }

  // ---- 核心:切換到指定索引 ----
  function goTo(index) {
    if (isAnimating) return;
    isAnimating = true;

    // 處理無縫循環邏輯
    if (index >= IMG_COUNT) index = 0;
    if (index < 0) index = IMG_COUNT - 1;

    const targetLeft = -index * IMG_WIDTH;

    $imgBox.animate({ left: targetLeft }, ANIM_DUR, function () {
      isAnimating = false;
    });

    // 同步指示器
    $indicators.find('li').removeClass(ACTIVE_CLS).eq(index).addClass(ACTIVE_CLS);
    currentIndex = index;
  }

  // ---- 下一張 / 上一張 ----
  function next() { goTo(currentIndex + 1); }
  function prev() { goTo(currentIndex - 1); }

  // ---- 自動播放控制 ----
  function startAuto() { stopAuto(); timerId = setInterval(next, INTERVAL); }
  function stopAuto()  { if (timerId) clearInterval(timerId); timerId = null; }

  // ---- 事件綁定 ----
  $next.on('click', next);
  $prev.on('click', prev);
  $indicators.on('click', 'li', function () { goTo($(this).data('index')); });
  $playBox.hover(stopAuto, startAuto); // 懸停暫停,離開繼續

  // ---- 啟動 ----
  initIndicators();
  startAuto();
});

關鍵技術點解析

技術點實現方式
無縫循環索引超界時重置為 0 或最後一張,配合 CSS `transition` 或 `animate` 視覺平滑
動畫隊列阻塞`isAnimating` 鎖 + `animate` 回調釋放,防止連點亂序
指示器同步每次切換 `removeClass` 全部再 `addClass` 當前
響應式適配容器寬度用 `%` + `window.resize` 重新計算 `IMG_WIDTH` 並 `goTo(currentIndex)`
觸控支援添加 `touchstart`/`touchmove`/`touchend` 計算滑動距離觸發 prev/next

現代化重構建議(無 jQuery 版)

  • 使用 **Swiper.js** / **Glide.js** / **Splide** 等成熟庫(體積小、觸控好、無依賴)。
  • 原生 JS 實現:`Element.animate()` (WAAPI) + `IntersectionObserver` 暫停/恢復 + CSS Scroll Snap。
  • 組件化:Vue 3 `` / React `` 封裝,Props 驅動,Slot 分發內容。

完整文件下載結構

banner-slider/
├── index.html
├── css/
│   └── slider.css
├── js/
│   └── slider.js
└── images/
    ├── banner01.jpg
    ├── banner02.jpg
    ├── banner03.jpg
    ├── banner04.jpg
    └── arrows.png
copyright © 萬盛學電腦網 all rights reserved