萬盛學電腦網

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

jQuery 實作仿 QQ 商城左右滾動焦點圖(輪播器)完整教學

經典的左右滾動焦點圖(Carousel/Slider)是首頁展示的核心元件。本文完整拆解結構、樣式、邏輯,並提供可直接生產環境使用的模組化寫法。

HTML 結構

<div class="focus" id="focus001">
  <ul class="slides">
    <li><a href="#"><img src="img/01.jpg" alt="標題 1"></a></li>
    <li><a href="#"><img src="img/02.jpg" alt="標題 2"></a></li>
    <li><a href="#"><img src="img/03.jpg" alt="標題 3"></a></li>
  </ul>
  <!-- 指示器、上下頁按鈕由 JS 動態插入 -->
</div>

CSS 關鍵樣式

.focus {
  position: relative;
  width: 800px; height: 280px;
  overflow: hidden;
  margin: 0 auto;
}
.slides {
  position: absolute;
  left: 0; top: 0;
  display: flex;           /* 現代排版:水平排列 */
  width: max-content;      /* 總寬度 = 單張寬度 × 數量 */
  transition: left 0.3s ease-out; /* 手動切換動畫 */
}
.slides li {
  flex: 0 0 800px;         /* 固定寬度等於容器 */
}
.slides img { width: 100%; height: 100%; object-fit: cover; }

/* 指示器 */
.indicators {
  position: absolute; bottom: 15px; left: 50%; transform: translateX(-50%);
  display: flex; gap: 8px; z-index: 10;
}
.indicators span {
  width: 12px; height: 12px; border-radius: 50%;
  background: rgba(255,255,255,0.5); cursor: pointer;
  transition: background 0.2s, transform 0.2s;
}
.indicators span.active { background: #fff; transform: scale(1.2); }

/* 上下頁箭頭 */
.nav-btn {
  position: absolute; top: 50%; transform: translateY(-50%);
  width: 40px; height: 40px; border-radius: 50%;
  background: rgba(0,0,0,0.3); color: #fff;
  border: none; cursor: pointer; font-size: 20px;
  opacity: 0; transition: opacity 0.3s;
}
.focus:hover .nav-btn { opacity: 0.7; }
.nav-btn.prev { left: 15px; }
.nav-btn.next { right: 15px; }

模組化 jQuery 外掛寫法

(function($) {
  $.fn.focusSlider = function(options) {
    const opts = $.extend({
      autoPlay: true,
      interval: 4000,
      speed: 300,
      easing: 'easeOutCubic'
    }, options);

    return this.each(function() {
      const $slider = $(this);
      const $slides = $slider.find('.slides');
      const $items = $slides.children('li');
      const len = $items.length;
      if (len <= 1) return;

      let index = 0;
      let timer = null;
      const slideWidth = $slider.width();

      // 1. 動態建立指示器與箭頭
      const $indicators = $('
').appendTo($slider); $items.each((i) => $indicators.append(`${i+1}`)); $('').appendTo($slider); $('').appendTo($slider); const $prev = $slider.find('.prev'); const $next = $slider.find('.next'); const $dots = $indicators.find('span'); // 2. 核心切換函式 function goTo(idx, animate = true) { index = (idx + len) % len; const targetLeft = -index * slideWidth; $slides.stop(true).animate({ left: targetLeft }, animate ? opts.speed : 0, opts.easing); $dots.removeClass('active').eq(index).addClass('active'); } // 3. 事件綁定 $dots.on('click', function() { goTo($(this).index()); }); $prev.on('click', () => goTo(index - 1)); $next.on('click', () => goTo(index + 1)); // 4. 自動播放 function startAuto() { if (!opts.autoPlay) return; timer = setInterval(() => goTo(index + 1), opts.interval); } function stopAuto() { clearInterval(timer); } $slider.hover(stopAuto, startAuto).trigger('mouseleave'); // 5. 鍵盤支援 $slider.on('keydown', function(e) { if (e.key === 'ArrowLeft') goTo(index - 1); else if (e.key === 'ArrowRight') goTo(index + 1); }); // 6. 響應式:視窗縮放重新計算寬度 $(window).on('resize', () => { slideWidth = $slider.width(); goTo(index, false); }); }); }; })(jQuery); // 使用方式 $(function() { $('#focus001').focusSlider({ interval: 5000 }); $('#focus002').focusSlider({ autoPlay: false }); });

進階功能擴充

  • 觸控滑動: 監聽 touchstart/touchmove/touchend 計算位移,結合 transform: translateX 實現跟手拖拽。
  • 無限循環: 複製首尾各一張到兩端,切換到複製項時瞬間跳回真實項(animate: false)。
  • 懶載入圖片: data-src + IntersectionObserver 或滾動事件載入。
  • 深度連結: 監聽 hashchange,URL 帶參數 #slide=2 直接跳轉。

現代替代方案

生產環境建議使用成熟庫:

  • Swiper:功能最全、效能最好、支援 SSR/React/Vue/Svelte
  • Flickity:觸控手感極佳、無依賴
  • tiny-slider:輕量(~10KB)、無 jQuery 依賴

理解原理後,無論自行開發或選用庫,都能根據專案需求做出最佳技術決策。

copyright © 萬盛學電腦網 all rights reserved