萬盛學電腦網

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

HTML5/JavaScript 實現無縫跑馬燈:IntersectionObserver、CSS Animation 與請求動畫幀的現代方案

從 `` 到現代無縫跑馬燈

HTML 標準已棄用 `` (非標準、無法控制、無障礙差)。現代實現採用 **CSS Animation + 複製節點** 或 **IntersectionObserver 觸發** 或 **requestAnimationFrame 精確控制**,實現高效能、可暫停、無障礙、響應式的無縫循環滾動。

方案一:純 CSS Animation (最簡潔、效能最佳、無 JS 依賴)

核心技巧:複製內容實現無縫銜接

<div class="marquee" aria-label="最新公告">
  <div class="marquee__track">
    <div class="marquee__content">
      <a href="/news/1">🎉 春季大促銷 全場 85 折</a>
      <a href="/news/2">📦 新品上市:輕量化筆記型電腦</a>
      <a href="/news/3">🔧 系統維護通知:5/20 凌晨 2-4 點</a>
    </div>
    <!-- 關鍵:複製一份內容,實現首尾無縫銜接 -->
    <div class="marquee__content" aria-hidden="true">
      <a href="/news/1">🎉 春季大促銷 全場 85 折</a>
      <a href="/news/2">📦 新品上市:輕量化筆記型電腦</a>
      <a href="/news/3">🔧 系統維護通知:5/20 凌晨 2-4 點</a>
    </div>
  </div>
</div>

<style>
.marquee {
  overflow: hidden;
  white-space: nowrap;
  background: #fff8e1;
  border: 1px solid #ffe082;
  border-radius: 8px;
  padding: 0.5rem 0;
  font-size: 0.95rem;
}
.marquee__track {
  display: flex;
  /* 動畫:將軌道向左移動一個內容寬度 (50%),利用複製內容實現無縫循環 */
  animation: marquee-scroll 20s linear infinite;
}
.marquee__content {
  display: flex;
  gap: 2rem; /* 項目間距 */
  padding: 0 1rem;
  flex-shrink: 0; /* 防止壓縮 */
}
.marquee a { color: #333; text-decoration: none; white-space: nowrap; }
.marquee a:hover { color: #e65100; text-decoration: underline; }

@keyframes marquee-scroll {
  from { transform: translateX(0); }
  to   { transform: translateX(-50%); } /* 移動一份內容寬度 */
}

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

/* 減弱動畫偏好 */
@media (prefers-reduced-motion: reduce) {
  .marquee__track { animation: none; }
  .marquee { overflow-x: auto; white-space: normal; } /* 退化為可捲動區域 */
}
</style>

關鍵點解析

  • 複製內容:`marquee__content` 出現兩次,動畫從 `translateX(0)` 移動到 `translateX(-50%)`,恰好移動一份內容寬度,循環時視覺無縫銜接。
  • 線性動畫:`linear` 保證勻速,`infinite` 無限循環。
  • 暫停互動:`:hover` 觸發 `animation-play-state: paused`,符合使用者預期。
  • 無障礙:`aria-label` 標記區域、複製內容 `aria-hidden="true"` 隱藏螢幕閱讀器、`prefers-reduced-motion` 尊重用戶偏好。
  • 響應式:內容寬度自適應,動畫距離以百分比計算,無需 JS 計算。

方案二:IntersectionObserver 觸發「進入視口才動畫」 (效能優化)

頁面有多個跑馬燈時,僅對進入視口的實例啟動動畫,離開視口暫停,節省 CPU/GPU。

const marquees = document.querySelectorAll('.marquee');
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        const track = entry.target.querySelector('.marquee__track');
        if (entry.isIntersecting) {
            track.style.animationPlayState = 'running';
        } else {
            track.style.animationPlayState = 'paused';
        }
    });
}, {rootMargin: '100px'}); // 提前 100px 啟動

marquees.forEach(m => observer.observe(m));

方案三:requestAnimationFrame 精確控制 (需互動控制、變速、拖拽時)

class MarqueeController {
    constructor(container) {
        this.container = container;
        this.track = container.querySelector('.marquee__track');
        this.content = container.querySelector('.marquee__content');
        this.speed = 50; // px/s
        this.pos = 0;
        this.rafId = null;
        this.paused = false;
        
        // 複製內容 (若 HTML 未預先複製)
        if (this.track.children.length === 1) {
            this.track.appendChild(this.content.cloneNode(true));
            this.track.children[1].setAttribute('aria-hidden', 'true');
        }
        this.contentWidth = this.content.getBoundingClientRect().width;
        
        container.addEventListener('mouseenter', () => this.pause());
        container.addEventListener('mouseleave', () => this.resume());
        this.start();
    }
    
    start() { this.tick(); }
    tick() {
        if (!this.paused) {
            this.pos -= this.speed / 60; // 假設 60fps
            if (this.pos <= -this.contentWidth) this.pos += this.contentWidth; // 循環
            this.track.style.transform = `translateX(${this.pos}px)`;
        }
        this.rafId = requestAnimationFrame(() => this.tick());
    }
    pause() { this.paused = true; }
    resume() { this.paused = false; }
    destroy() { cancelAnimationFrame(this.rafId); }
}

// 初始化
document.querySelectorAll('.marquee').forEach(el => new MarqueeController(el));

垂直向無縫滾動 (公告列表)

<div class="marquee-vertical">
  <ul class="marquee__track">
    <li><a href="#">公告一</a></li>
    <li><a href="#">公告二</a></li>
    <li><a href="#">公告三</a></li>
    <!-- 複製 -->
    <li aria-hidden="true"><a href="#">公告一</a></li>
    <li aria-hidden="true"><a href="#">公告二</a></li>
    <li aria-hidden="true"><a href="#">公告三</a></li>
  </ul>
</div>

<style>
.marquee-vertical { height: 200px; overflow: hidden; }
.marquee-vertical .marquee__track {
  display: flex; flex-direction: column; gap: 0.5rem;
  animation: marquee-vertical 15s linear infinite;
}
@keyframes marquee-vertical {
  from { transform: translateY(0); }
  to   { transform: translateY(-50%); }
}
.marquee-vertical:hover .marquee__track { animation-play-state: paused; }
</style>

總結與選型建議

方案適用場景優點缺點
純 CSS Animation90% 場景:公告欄、品牌滾動、標語輪播零 JS、效能極佳、主執行緒零負擔、易維護無法動態調整速度、無法對外暴露控制 API
IntersectionObserver + CSS長頁面多跑馬燈、離螢幕暫停省資源智能啟停、仍以 CSS 驅動為主需少量 JS、舊瀏覽器需 Polyfill
requestAnimationFrame需程式化控制:變速、倒轉、拖拽暫停、外部按鈕控制、與 Canvas/WebGL 同步完全控制、可整合遊戲迴圈JS 主執行緒持續佔用、需自行處理效能

**首選純 CSS 方案**,滿足絕大多數需求。只有當需要「程式化控制速度/方向/暫停/繼續」或「與其他動畫系統同步」時,才引入 JS 控制器。

copyright © 萬盛學電腦網 all rights reserved