萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 文字向上循環滾動 (Marquee 效果) 現代實作:CSS Animation 替代方案

傳統 <marquee> 標籤已從 HTML 標準移除 (非標準、無障礙差、不可控)。現代 Web 開發應使用 CSS Animation 或 JavaScript Intersection Observer 實現無障礙、高效能、可控制的文字滾動效果。

核心需求分析

  • 文字內容向上循環滾動
  • 滾動速度可控、可暫停/繼續
  • 滑鼠懸停暫停、離開繼續
  • 無障礙:支援 prefers-reduced-motion、鍵盤可操作、螢幕閱讀器友善
  • 響應式:容器高度自適應、文字截斷處理

方案一:純 CSS Animation (首選、效能最佳)

HTML 結構

<div class="marquee-vertical" aria-label="最新消息滾動">
    <div class="marquee-content">
        <p>最新公告:系統將於今晚 22:00 進行例行維護,預計 30 分鐘。</p>
        <p>新功能上線:會員積分可兌換禮品,詳情請見活動專區。</p>
        <p>重要提醒:請盡快完成實名認證,避免影響帳戶功能。</p>
        <p>優惠活動:雙十一全場 85 折,會員再享 9 折優惠。</p>
        <p>服務通知:客服專線調整為 0800-123-456,24 小時服務。</p>
    </div>
</div>

CSS 實作

.marquee-vertical {
    height: 200px;                 /* 可見區域高度 */
    overflow: hidden;              /* 隱藏超出內容 */
    position: relative;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background: #fafafa;
    font-family: 'Microsoft JhengHei', sans-serif;
}

.marquee-content {
    display: flex;
    flex-direction: column;
    width: 100%;
    /* 動畫:向上移動一個完整內容高度 */
    animation: marqueeUp 20s linear infinite;
    /* 暫停控制 */
    animation-play-state: running;
}

.marquee-content p {
    margin: 0;
    padding: 12px 16px;
    line-height: 1.6;
    border-bottom: 1px solid #eee;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 複製一份內容實現無縫循環 (關鍵技巧) */
.marquee-content::after {
    content: '';
    display: block;
    /* 這裡用 JS 動態複製內容更佳,純 CSS 需手動重複 HTML */
}

/* 關鍵幀:向上移動 50% (因內容複製雙份) */
@keyframes marqueeUp {
    0% { transform: translateY(0); }
    100% { transform: translateY(-50%); }
}

/* 滑鼠懸停暫停 */
.marquee-vertical:hover .marquee-content {
    animation-play-state: paused;
}

/* 聚焦時也暫停 (鍵盤無障礙) */
.marquee-vertical:focus-within .marquee-content {
    animation-play-state: paused;
}

/* 尊重用戶減少動畫偏好 */
@media (prefers-reduced-motion: reduce) {
    .marquee-content { animation: none; }
}

無縫循環關鍵:內容複製

CSS 動畫從 0 移動到 -50% 需要內容重複兩份。建議用 JS 複製:

const marquee = document.querySelector('.marquee-content');
const originalHTML = marquee.innerHTML;
marquee.innerHTML = originalHTML + originalHTML; // 雙份內容

方案二:JavaScript 控制 (高互動、動態資料)

<div id="jsMarquee" class="marquee-vertical" role="region" aria-live="polite" aria-label="公告滾動">
    <div class="marquee-track"></div>
</div>

<script>
class VerticalMarquee {
    constructor(containerSelector, items, options = {}) {
        this.container = document.querySelector(containerSelector);
        this.track = this.container.querySelector('.marquee-track');
        this.items = items;
        this.speed = options.speed || 50; // px/s
        this.pauseOnHover = options.pauseOnHover !== false;
        this.direction = options.direction || 'up'; // 'up' | 'down'
        this.animationId = null;
        this.isPaused = false;
        this.lastTime = 0;
        this.position = 0;
        this.itemHeight = 0;
        
        this.init();
    }
    
    init() {
        // 建立雙份項目
        this.renderItems();
        this.renderItems(); // 複製第二份
        this.itemHeight = this.track.querySelector('.marquee-item').offsetHeight;
        this.totalHeight = this.track.scrollHeight / 2; // 單份高度
        
        // 事件綁定
        if (this.pauseOnHover) {
            this.container.addEventListener('mouseenter', () => this.pause());
            this.container.addEventListener('mouseleave', () => this.resume());
            this.container.addEventListener('focusin', () => this.pause());
            this.container.addEventListener('focusout', () => this.resume());
        }
        
        // 尊重減少動畫
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            this.pause();
            return;
        }
        
        this.animate(performance.now());
    }
    
    renderItems() {
        this.items.forEach(text => {
            const div = document.createElement('div');
            div.className = 'marquee-item';
            div.textContent = text;
            this.track.appendChild(div);
        });
    }
    
    animate(time) {
        if (this.isPaused) {
            this.animationId = requestAnimationFrame((t) => this.animate(t));
            return;
        }
        
        const delta = (time - this.lastTime) / 1000; // 秒
        this.lastTime = time;
        
        const distance = this.speed * delta * (this.direction === 'up' ? -1 : 1);
        this.position += distance;
        
        // 循環邏輯
        if (this.direction === 'up') {
            if (Math.abs(this.position) >= this.totalHeight) {
                this.position += this.totalHeight;
            }
        } else {
            if (this.position >= 0) {
                this.position -= this.totalHeight;
            }
        }
        
        this.track.style.transform = `translateY(${this.position}px)`;
        this.animationId = requestAnimationFrame((t) => this.animate(t));
    }
    
    pause() { this.isPaused = true; }
    resume() { this.isPaused = false; this.lastTime = performance.now(); }
    destroy() { cancelAnimationFrame(this.animationId); }
}

// 使用範例
const news = [
    '系統維護公告:今晚 22:00-22:30 暫停服務',
    '新功能:會員積分兌換商城正式上線',
    '重要:請於 12/31 前完成實名認證',
    '優惠:年終慶全場 85 折,會員雙重優惠',
    '客服專線更新:0800-123-456 (24小時)'
];

document.addEventListener('DOMContentLoaded', () => {
    window.marquee = new VerticalMarquee('#jsMarquee', news, { speed: 40 });
});
</script>

方案三:Intersection Observer 觸發進入視窗動畫 (進階)

適用於「滾動進視窗才開始滾動」的節能模式:

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('animate');
        } else {
            entry.target.classList.remove('animate');
        }
    });
}, { threshold: 0.5 });

document.querySelectorAll('.marquee-vertical').forEach(el => observer.observe(el));

無障礙 (a11y) 完整檢查清單

準則實作方式
語意標記role="region" aria-label="..." aria-live="polite"
鍵盤可操作tabindex="0"、Space 暫停/播放、Esc 停止
減少動畫@media (prefers-reduced-motion: reduce) 禁用動畫
聚焦管理:focus-within 暫停、焦點指示器可見
內容可選取暫停時可複製文字、連結可點擊
語言宣告<html lang="zh-TW">

效能對比

方案主執行緒負載記憶體控制精度無障礙推薦場景
CSS Animation極低 (合成器線程)低中 (難精確暫停/求值)良 (需額外處理)靜態公告、簡單循環
JS requestAnimationFrame低 (每幀計算)中高 (精確控制、動態速度)優 (完整事件控制)動態資料、互動豐富
<marquee> (棄用)高 (瀏覽器內建)高無差禁止使用

總結

文字向上循環滾動的現代最佳實踐:靜態內容用 CSS Animation + 內容雙份複製 + prefers-reduced-motion;動態/互動需求用 JS requestAnimationFrame 類別封裝。徹底拋棄 <marquee>,擁抱標準、無障礙、可維護的 Web 動畫技術棧。

copyright © 萬盛學電腦網 all rights reserved