萬盛學電腦網

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

JavaScript + jQuery 實現文章標題定時輪播切換效果

效果描述

標題列表中每隔固定時間(如 1.85 秒)自動切換顯示下一條,循環播放,滑鼠懸停可暫停(可選增強)。

完整實現代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>標題輪播演示</title>
<style>
#jokeTitle li { display: none; line-height: 1.8; }
#jokeTitle li.active { display: block; }
</style>
</head>
<body>
<div>
    <ul id="jokeTitle">
        <li class="line">標題一:JavaScript 進階技巧</li>
        <li class="line">標題二:CSS 佈局新特性</li>
        <li class="line">標題三:Node.js 實戰指南</li>
    </ul>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
    var titleRotator = {
        $items: $('#jokeTitle li'),
        intervalId: null,
        currentIndex: 0,
        intervalMs: 1850,

        init: function() {
            this.bindHoverPause();
            this.start();
        },

        show: function(index) {
            this.$items.removeClass('active').eq(index).addClass('active');
        },

        next: function() {
            this.currentIndex = (this.currentIndex + 1) % this.$items.length;
            this.show(this.currentIndex);
        },

        start: function() {
            this.show(0); // 初始顯示第一條
            var self = this;
            this.intervalId = setInterval(function() {
                self.next();
            }, this.intervalMs);
        },

        stop: function() {
            clearInterval(this.intervalId);
            this.intervalId = null;
        },

        bindHoverPause: function() {
            var self = this;
            $('#jokeTitle').hover(
                function() { self.stop(); },      // mouseenter
                function() { self.start(); }      // mouseleave
            );
        }
    };

    titleRotator.init();
});
</script>
</body>
</html>

核心邏輯解析

  • 狀態封裝:用對象字面量封裝狀態(currentIndex、intervalId)與方法,避免全局變量污染。
  • 取模運算:(index + 1) % length 實現循環切換。
  • CSS 控制顯隱:.active 類控制 display,比 show()/hide() 更利於動畫擴展。
  • 懸停暫停:hover(enterHandler, leaveHandler) 增強用戶體驗。

擴展功能建議

  • 淡入淡出動畫:.fadeOut(200).eq(idx).fadeIn(200) 或 CSS transition: opacity。
  • 手動控制按鈕:上一條/下一條、播放/暫停。
  • 數據驅動:從 API 獲取標題列表動態渲染 <li>。
  • 無障礙:aria-live="polite" 輔助技術朗讀切換內容。

原生 JS 輕量版(無 jQuery 依賴)

const items = document.querySelectorAll('#jokeTitle li');
let idx = 0, timer;

function show(i) {
    items.forEach((el, n) => el.style.display = n === i ? 'block' : 'none');
}

function next() {
    idx = (idx + 1) % items.length;
    show(idx);
}

function start() {
    show(0);
    timer = setInterval(next, 1850);
}

function stop() { clearInterval(timer); }

document.getElementById('jokeTitle').addEventListener('mouseenter', stop);
document.getElementById('jokeTitle').addEventListener('mouseleave', start);

start();

根據專案依賴情況選擇 jQuery 或原生版本,邏輯核心完全一致。

copyright © 萬盛學電腦網 all rights reserved