垂直跑馬燈式新聞滾動是常見 UI 需求。現代瀏覽器支援 requestAnimationFrame、CSS 動畫與 IntersectionObserver,本文提供**零依賴、無 jQuery、語意化 HTML、無障礙友善**的完整實作。
<div class="news-ticker" aria-live="polite" aria-atomic="false">
<ul class="news-list">
<li><a href="/news/1">請教高手幫我看下這段代碼:FLASH顯示不了</a></li>
<li><a href="/news/2">請教在 UTF-8 編輯下的符號顯示問題</a></li>
<li><a href="/news/3">jQuery 做的一個滑動效果,不知如何增加延遲</a></li>
<li><a href="/news/4">技術研究:QQ2009版按鈕漸顯漸隱的由來</a></li>
<li><a href="/news/5">Javascript 讀取 Json 數據並分頁顯示</a></li>
</ul>
</div>
.news-ticker {
overflow: hidden;
height: 1.5rem; /* 單行高度 */
line-height: 1.5rem;
font-size: 0.875rem;
border: 1px solid #ddd;
border-radius: 4px;
background: #fafafa;
position: relative;
}
.news-list {
list-style: none;
margin: 0; padding: 0;
display: flex;
flex-direction: column;
animation: scroll-up 20s linear infinite;
/* 滑鼠懸停暫停 */
}
.news-ticker:hover .news-list,
.news-ticker:focus-within .news-list {
animation-play-state: paused;
}
@keyframes scroll-up {
from { transform: translateY(0); }
to { transform: translateY(-50%); } /* 列表複製一次後位移 50% 實現無縫循環 */
}
/* 無障礙:減少動畫偏好 */
@media (prefers-reduced-motion: reduce) {
.news-list { animation: none; }
}
document.querySelectorAll('.news-ticker').forEach(ticker => {
const list = ticker.querySelector('.news-list');
if (!list) return;
// 複製子節點以實現無縫循環
list.innerHTML += list.innerHTML;
// 計算單行高度,動態調整動畫時長 (可選)
const itemHeight = list.firstElementChild?.offsetHeight || 24;
const totalItems = list.children.length / 2; // 原始項目數
const duration = totalItems * 3; // 每項 3 秒
list.style.animationDuration = `${duration}s`;
// 鍵盤焦點進入時暫停
list.addEventListener('focusin', () => list.style.animationPlayState = 'paused');
list.addEventListener('focusout', () => list.style.animationPlayState = 'running');
});
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const list = entry.target.querySelector('.news-list');
if (entry.isIntersecting) list.style.animationPlayState = 'running';
else list.style.animationPlayState = 'paused';
});
}, { rootMargin: '0px', threshold: 0.1 });
document.querySelectorAll('.news-ticker').forEach(ticker => observer.observe(ticker));
aria-live="polite":螢幕閱讀器自動播報新增內容。prefers-reduced-motion:尊重使用者減少動畫偏好。<ul><li><a> 結構,非單純 <div> 堆疊。linear,且位移距離精確為列表總高度 50% (因已複製一次)。text-overflow: ellipsis; white-space: nowrap; overflow: hidden; 於 li > a。fetch('/api/news').then(r => r.json()).then(data => { list.innerHTML = data.map(...).join('') + data.map(...).join(''); }) 重新複製一次。純 CSS + 少量 JS 即可實現高效能、無障礙、可維護的垂直新聞滾動,摒棄舊式 setInterval 操作 DOM 的低效寫法。