萬盛學電腦網

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

原生 JS 與 jQuery 雙版本實現圖片輪播淡入淡出效果

效果預覽

經典 Banner 輪播:多張圖片淡入淡出切換,底部半透明遮罩顯示標題,右下角圓點指示器同步高亮,支援滑鼠懸停暫停、點擊指示器切換、自動循環。

輪播結構示意圖 輪播效果截圖

HTML 結構(兩版通用)

<div class="wrapper">
    <div class="banner">
        <ul class="imgList">
            <li class="imgOn"><a href="#"><img src="./img/test1.jpg" width="400" height="200" alt="puss in boots1"></a></li>
            <li><a href="#"><img src="./img/test2.jpg" width="400" height="200" alt="puss in boots2"></a></li>
            <li><a href="#"><img src="./img/test3.jpg" width="400" height="200" alt="puss in boots3"></a></li>
            <li><a href="#"><img src="./img/test4.jpg" width="400" height="200" alt="puss in boots4"></a></li>
            <li><a href="#"><img src="./img/test5.jpg" width="400" height="200" alt="puss in boots5"></a></li>
        </ul>
        <div class="bg"></div> <!-- 半透明遮罩 -->
        <ul class="infoList">
            <li class="infoOn">puss in boots1</li>
            <li>puss in boots2</li>
            <li>puss in boots3</li>
            <li>puss in boots4</li>
            <li>puss in boots5</li>
        </ul>
        <ul class="indexList">
            <li class="indexOn">1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
    </div>
</div>

CSS 關鍵樣式

.wrapper { position: relative; margin: 30px auto; width: 400px; height: 200px; }
.banner { width: 400px; height: 200px; overflow: hidden; } /* 關鍵:防止 fadeIn 瞬間超高 */
.imgList { width: 400px; height: 200px; z-index: 10; }
.imgList li { display: none; position: absolute; top: 0; left: 0; }
.imgList .imgOn { display: block; }
.bg { position: absolute; bottom: 0; width: 400px; height: 40px; z-index: 20; background: #000; opacity: 0.4; }
.infoList { position: absolute; left: 10px; bottom: 10px; z-index: 30; }
.infoList li { display: none; color: #fff; }
.infoList .infoOn { display: inline; }
.indexList { position: absolute; right: 10px; bottom: 5px; z-index: 30; }
.indexList li { float: left; margin-right: 5px; padding: 2px 8px; border: 2px solid #000; background: #888; cursor: pointer; }
.indexList .indexOn { background: #f00; color: #fff; font-weight: bold; }

版本一:jQuery 實現(簡潔)

$(function() {
    var $imgLi = $(".imgList li"), $infoLi = $(".infoList li"), $idxLi = $(".indexList li");
    var cur = 0, len = $imgLi.length, timer;

    function switchTo(n) {
        $imgLi.removeClass("imgOn").hide().eq(n).fadeIn().addClass("imgOn");
        $infoLi.removeClass("infoOn").eq(n).addClass("infoOn");
        $idxLi.removeClass("indexOn").eq(n).addClass("indexOn");
        cur = n;
    }

    // 自動輪播
    function auto() {
        timer = setInterval(function() {
            switchTo((cur + 1) % len);
        }, 2500);
    }
    auto();

    // 指示器點擊
    $idxLi.click(function() {
        clearInterval(timer);
        switchTo($(this).index());
        auto();
    });

    // 懸停暫停
    $(".banner").hover(function() { clearInterval(timer); }, auto);
});

版本二:原生 JS 實現(零依賴)

(function() {
    var wrapper = document.querySelector('.wrapper');
    var imgLi = wrapper.querySelectorAll('.imgList li');
    var infoLi = wrapper.querySelectorAll('.infoList li');
    var idxLi = wrapper.querySelectorAll('.indexList li');
    var len = imgLi.length, cur = 0, timer;

    // 簡易 fadeIn/fadeOut 實現
    function fadeIn(el) {
        el.style.display = 'block';
        el.style.opacity = 0;
        var tick = function() {
            var op = parseFloat(el.style.opacity) + 0.1;
            el.style.opacity = op;
            if (op < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
    }
    function fadeOut(el, callback) {
        var op = 1;
        var tick = function() {
            op -= 0.1;
            el.style.opacity = op;
            if (op > 0) requestAnimationFrame(tick);
            else { el.style.display = 'none'; callback && callback(); }
        };
        requestAnimationFrame(tick);
    }

    function switchTo(n) {
        if (n === cur) return;
        fadeOut(imgLi[cur], function() {
            imgLi[cur].classList.remove('imgOn');
            fadeIn(imgLi[n]);
            imgLi[n].classList.add('imgOn');
        });
        infoLi[cur].classList.remove('infoOn'); infoLi[n].classList.add('infoOn');
        idxLi[cur].classList.remove('indexOn'); idxLi[n].classList.add('indexOn');
        cur = n;
    }

    function auto() {
        timer = setInterval(function() { switchTo((cur + 1) % len); }, 2500);
    }
    auto();

    // 指示器事件代理
    wrapper.querySelector('.indexList').addEventListener('click', function(e) {
        if (e.target.tagName === 'LI') {
            clearInterval(timer);
            switchTo(Array.prototype.indexOf.call(idxLi, e.target));
            auto();
        }
    });

    // 懸停暫停
    wrapper.querySelector('.banner').addEventListener('mouseenter', function() { clearInterval(timer); });
    wrapper.querySelector('.banner').addEventListener('mouseleave', auto);
})();

對比總結

維度jQuery 版原生 JS 版
代碼量~30 行~60 行(含 fade 封裝)
依賴jQuery 3.x+無
動畫內建 `fadeIn/out`,GPU 加速手寫 `requestAnimationFrame` 漸變
相容性IE9+IE10+ (需 polyfill `classList`/`requestAnimationFrame`)
學習價值API 熟悉度理解動畫幀、閉包、事件代理

進階擴展建議

  • 觸控滑動支援(`touchstart`/`move`/`end` 計算位移切換)。
  • 響應式:圖片 `max-width:100%` + 容器百分比寬度。
  • 無障礙:`role="region" aria-roledescription="carousel"`、鍵盤左右鍵切換。
  • 圖片懶載入:`data-src` + `IntersectionObserver`。
copyright © 萬盛學電腦網 all rights reserved