效果展示
- 公告列表垂直向上滾動
- 第一項移至底部,形成無縫循環
- 可控制間隔時間、動畫緩動
核心程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>垂直公告滾動</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { padding: 20px; font-family: 'Microsoft JhengHei', sans-serif; }
.marquee-box { width: 300px; height: 180px; border: 1px solid #ddd; overflow: hidden; position: relative; }
.marquee-list { list-style: none; position: absolute; top: 0; left: 0; width: 100%; }
.marquee-list li { line-height: 30px; padding: 0 15px; border-bottom: 1px solid #eee; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.marquee-list li:last-child { border-bottom: none; }
.marquee-list li:hover { background: #f5f5f5; cursor: pointer; }
</style>
</head>
<body>
<h3>最新公告</h3>
<div class="marquee-box">
<ul class="marquee-list" id="noticeList">
<li>🎉 系統維護公告:今晚 02:00-04:00 暫停服務</li>
<li>📢 新功能上線:支援多語言切換</li>
<li>⚠️ 安全提醒:請定期更換密碼</li>
<li>📅 活動預告:雙十一優惠活動即將開跑</li>
<li>🔧 修復已知 Bug:登入頁面驗證碼問題</li>
<li>💡 使用技巧:善用快捷鍵提升效率</li>
</ul>
</div>
<script>
$(function() {
const $list = $('#noticeList');
const itemHeight = 30; // li line-height
const visibleCount = 6; // 可見項目數
const intervalMs = 2500; // 輪播間隔
const animateMs = 500; // 動畫時長
let timer = null;
let isHover = false;
function scrollUp() {
if (isHover) return; // 滑鼠懸停暫停
const $first = $list.children('li:first');
const height = $first.outerHeight(true); // 含 margin
// 動畫向上移動
$list.animate({top: -height}, animateMs, 'linear', function() {
// 動畫完成:移動第一項到最後
$first.appendTo($list);
$list.css('top', 0); // 重置位置
});
}
// 啟動定時器
function start() {
timer = setInterval(scrollUp, intervalMs);
}
function stop() {
clearInterval(timer);
timer = null;
}
// 滑鼠進入/離開控制
$('.marquee-box').hover(
() => { isHover = true; stop(); },
() => { isHover = false; start(); }
);
// 頁面可見性 API:切換分頁時暫停
document.addEventListener('visibilitychange', () => {
if (document.hidden) stop();
else start();
});
start();
});
</script>
</body>
</html>
進階版:支援動態資料載入
class VerticalMarquee {
constructor(selector, options = {}) {
this.$container = $(selector);
this.$list = this.$container.find('ul');
this.options = Object.assign({
itemHeight: 30,
interval: 3000,
animateDuration: 600,
easing: 'linear',
pauseOnHover: true,
apiUrl: null,
apiParams: {},
renderItem: (item) => `${item.title}`
}, options);
this.timer = null;
this.isHover = false;
this.init();
}
init() {
this.bindEvents();
if (this.options.apiUrl) this.loadData();
else this.start();
}
async loadData() {
try {
const res = await $.ajax(this.options.apiUrl, {data: this.options.apiParams});
const html = res.data.map(this.options.renderItem).join('');
this.$list.html(html);
this.start();
} catch (err) {
console.error('載入公告失敗:', err);
this.$list.html('載入失敗');
}
}
scroll() {
if (this.isHover || this.$list.children().length <= 1) return;
const $first = this.$list.children('li:first');
const height = $first.outerHeight(true);
this.$list.animate({top: -height}, this.options.animateDuration, this.options.easing, () => {
$first.appendTo(this.$list);
this.$list.css('top', 0);
});
}
start() {
this.stop();
this.timer = setInterval(() => this.scroll(), this.options.interval);
}
stop() {
clearInterval(this.timer);
this.timer = null;
}
bindEvents() {
if (this.options.pauseOnHover) {
this.$container.hover(
() => { this.isHover = true; this.stop(); },
() => { this.isHover = false; this.start(); }
);
}
document.addEventListener('visibilitychange', () => {
document.hidden ? this.stop() : this.start();
});
}
destroy() {
this.stop();
this.$container.off('mouseenter mouseleave');
}
}
// 使用
const marquee = new VerticalMarquee('#noticeList', {
apiUrl: '/api/announcements',
apiParams: {limit: 20, category: 'news'},
renderItem: item => `[${item.category}] ${item.title}`
});
無 jQuery 版本 (Vanilla JS)
function createMarquee(containerSelector, options = {}) {
const container = document.querySelector(containerSelector);
const list = container.querySelector('ul');
const opts = Object.assign({
interval: 3000,
animateDuration: 500,
pauseOnHover: true
}, options);
let timer = null;
let isHover = false;
function scroll() {
if (isHover || list.children.length <= 1) return;
const first = list.firstElementChild;
const height = first.offsetHeight + parseInt(getComputedStyle(first).marginBottom);
// 使用 Web Animations API
first.animate([
{transform: 'translateY(0)', offset: 0},
{transform: `translateY(-${height}px)`, offset: 1}
], {duration: opts.animateDuration, easing: 'linear', fill: 'forwards'})
.onfinish = () => {
list.appendChild(first);
first.style.transform = ''; // 清除 transform
};
}
function start() { timer = setInterval(scroll, opts.interval); }
function stop() { clearInterval(timer); timer = null; }
if (opts.pauseOnHover) {
container.addEventListener('mouseenter', () => { isHover = true; stop(); });
container.addEventListener('mouseleave', () => { isHover = false; start(); });
}
document.addEventListener('visibilitychange', () => document.hidden ? stop() : start());
start();
return {start, stop, destroy: stop};
}
常見問題解決
| 問題 | 解決方案 |
| 動畫卡頓 | 使用 `transform: translateY` 而非 `top`,啟用 GPU 加速 |
| 滾動閃爍 | 確保容器 `overflow: hidden`,列表 `position: absolute` |
| 項目高度不一 | 用 `outerHeight(true)` 取得實際高度,或設定固定 `line-height` |
| 動態新增項目 | 重新計算或使用 MutationObserver 監聽 DOM 變化 |