萬盛學電腦網

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

jQuery 實現仿 QQ 商城焦點圖輪播:左右按鈕、數字索引、自動播放、鼠標暫停

功能特性

  • 無縫左右滾動切換
  • 數字索引按鈕(支持 hover 切換)
  • 左右箭頭按鈕(透明度過渡)
  • 自動輪播(間隔可配置)
  • 鼠標進入暫停,離開恢復
  • 響應式寬度適配

HTML 結構


<div id="focus" class="focus-slider">
    <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>
        <li><a href="#"><img src="img/04.jpg" alt="標題4"></a></li>
        <li><a href="#"><img src="img/05.jpg" alt="標題5"></a></li>
    </ul>
    <!-- 控制元素由 JS 動態生成 -->
</div>

CSS 樣式(精簡核心)


.focus-slider {
    position: relative;
    width: 100%;           /* 響應式寬度 */
    height: 280px;
    overflow: hidden;
    background: #000;
}
.focus-slider .slides {
    position: absolute;
    left: 0; top: 0;
    height: 100%;
    display: flex;         /* 現代瀏覽器用 flex 布局橫向排列 */
}
.focus-slider .slides li {
    flex: 0 0 100%;        /* 每張佔滿容器寬度 */
    width: 100%;
    height: 100%;
}
.focus-slider .slides img {
    width: 100%; height: 100%; object-fit: cover; display: block;
}

/* 動態生成的控制器樣式 */
.focus-slider .btnBg { position:absolute; left:0; bottom:0; width:100%; height:20px; background:#000; opacity:.5; }
.focus-slider .btn { position:absolute; right:0; bottom:0; padding:5px 10px; text-align:right; z-index:10; }
.focus-slider .btn span { display:inline-block; width:25px; height:10px; margin-left:5px; background:#fff; cursor:pointer; opacity:.4; border-radius:2px; }
.focus-slider .btn span.on { opacity:1; background:#fff; }
.focus-slider .preNext { position:absolute; top:50%; transform:translateY(-50%); width:45px; height:100px; background:url(sprite.png) no-repeat; cursor:pointer; opacity:.2; z-index:10; transition:opacity .3s; }
.focus-slider .preNext:hover { opacity:.5; }
.focus-slider .pre { left:0; background-position:0 0; }
.focus-slider .next { right:0; background-position:right top; }

核心 JS 邏輯(模塊化封裝)


class FocusSlider {
    constructor(container, options = {}) {
        this.$container = $(container);
        this.$slides = this.$container.find('.slides');
        this.$items = this.$slides.children('li');
        this.len = this.$items.length;
        this.index = 0;
        this.timer = null;
        this.opts = $.extend({
            autoPlay: true,
            interval: 4000,
            speed: 300,
            easing: 'swing'
        }, options);
        
        if (this.len <= 1) return; // 單張無需輪播
        this._init();
    }
    
    _init() {
        this._createControls();
        this._bindEvents();
        this._setWidth();
        this._show(0); // 初始顯示第一張
        if (this.opts.autoPlay) this._startAuto();
    }
    
    _createControls() {
        // 數字按鈕
        let btnHtml = '
'; for (let i = 0; i < this.len; i++) btnHtml += ''; btnHtml += '
'; // 箭頭 btnHtml += '
'; this.$container.append(btnHtml); this.$btnBg = this.$container.find('.btnBg'); this.$btns = this.$container.find('.btn span'); this.$pre = this.$container.find('.pre'); this.$next = this.$container.find('.next'); } _bindEvents() { // 數字按鈕 hover this.$btns.hover((e) => { this.index = this.$btns.index(e.currentTarget); this._show(this.index); }); // 箭頭點擊 this.$pre.click(() => this._prev()); this.$next.click(() => this._next()); // 箭頭透明度 hover (CSS transition 已處理,JS 可省略) // 容器 hover 暫停/恢復 this.$container.hover( () => this._stopAuto(), () => this._startAuto() ); } _setWidth() { // 寬度 = 容器寬度 * 數量(用於左側滾動) this.slideWidth = this.$container.width(); this.$slides.width(this.slideWidth * this.len); this.$items.width(this.slideWidth); } _show(index) { // 邊界處理 if (index >= this.len) index = 0; if (index < 0) index = this.len - 1; this.index = index; // 滾動 ul const left = -index * this.slideWidth; this.$slides.stop(true, false).animate({ left }, this.opts.speed, this.opts.easing); // 按鈕高亮 this.$btns.stop(true, false).animate({ opacity: 0.4 }, this.opts.speed) .eq(index).stop(true, false).animate({ opacity: 1 }, this.opts.speed); } _prev() { this._show(this.index - 1); } _next() { this._show(this.index + 1); } _startAuto() { this._stopAuto(); this.timer = setInterval(() => { this._next(); }, this.opts.interval); } _stopAuto() { clearInterval(this.timer); this.timer = null; } destroy() { this._stopAuto(); this.$container.off('.focusSlider'); this.$container.find('.btnBg, .btn, .preNext').remove(); this.$slides.css({ left: 0, width: '' }); this.$items.css({ width: '' }); } } // 響應式:窗口變化重新計算寬度 $(window).on('resize', () => { if (window.focusSlider) window.focusSlider._setWidth(); }); // 初始化 $(function() { window.focusSlider = new FocusSlider('#focus', { interval: 4000, speed: 300 }); });

進階優化點

  1. 無縫循環:複製首尾項實現真正無限循環(當前方案跳轉有閃動)
  2. 觸摸滑動支持:添加 touchstart/move/end 事件,移動端手勢切換
  3. 懶加載圖片:data-src + IntersectionObserver 按需加載
  4. 鍵盤導航:左/右鍵切換,Tab 聚焦控制器
  5. 無障礙:role="region" aria-roledescription="輪播"、aria-label、aria-live
  6. CSS Transform 替代 left:transform: translateX(-${index*100}%) 啟用 GPU 加速

現代無依賴版本(ES6 + CSS Transform)


// 核心邏輯同理,將 $el.animate({left}) 改為
this.$slides.style.transform = `translateX(-${index * 100}%)`;
this.$slides.style.transition = `transform ${speed}ms ${easing}`;
// 配合 requestAnimationFrame 處理自動播放

總結

焦點圖輪播是前端經典組件。核心邏輯:**寬度計算 → 索引狀態 → 位移動畫 → 控制器同步 → 自動播放狀態機**。封裝為 FocusSlider 類,配置化參數,暴露 destroy(),即得生產級組件。現代開發建議使用 transform + transition 替代 left + animate,並集成觸摸、無障礙、懶加載等增強特性。

copyright © 萬盛學電腦網 all rights reserved