標題列表中每隔固定時間(如 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 實現循環切換。.active 類控制 display,比 show()/hide() 更利於動畫擴展。hover(enterHandler, leaveHandler) 增強用戶體驗。.fadeOut(200).eq(idx).fadeIn(200) 或 CSS transition: opacity。<li>。aria-live="polite" 輔助技術朗讀切換內容。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 或原生版本,邏輯核心完全一致。