<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>單行文字向上滾動</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.scroll-box {
height: 30px; line-height: 30px;
border: 1px solid #ddd; overflow: hidden;
width: 400px; margin: 20px auto; padding: 0 10px;
background: #fafafa;
}
.scroll-box ul { margin: 0; padding: 0; list-style: none; }
.scroll-box li { height: 30px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.scroll-box a { color: #333; text-decoration: none; }
.scroll-box a:hover { color: #007bff; }
</style>
</head>
<body>
<div id="newsTicker" class="scroll-box">
<ul>
<li><a href="#">最新公告:系統將於今晚 22:00-24:00 進行維護升級</a></li>
<li><a href="#">新功能上線:支援多語言切換與深色模式</a></li>
<li><a href="#">活動通知:雙十一大促提前預熱,領券最高減 500</a></li>
<li><a href="#">安全提醒:請勿輕信不明連結,啟用雙因子認證保護帳戶</a></li>
</ul>
</div>
<script>
function autoScroll($container) {
var $ul = $container.find('ul:first');
var liHeight = $ul.find('li:first').outerHeight(); // 含 margin
$ul.animate({ marginTop: -liHeight }, 500, function() {
// 動畫完成:第一項移至末尾、margin 歸零
$(this).css('marginTop', 0).children('li:first').appendTo(this);
});
}
$(function() {
var $box = $('#newsTicker');
// 滑鼠懸停暫停
var timer = setInterval(function() { autoScroll($box); }, 3000);
$box.hover(
function() { clearInterval(timer); },
function() { timer = setInterval(function() { autoScroll($box); }, 3000); }
);
});
</script>
</body>
</html>
animate({marginTop: -liHeight}):向上移動一個 li 高度。complete 回調中:
css('marginTop', 0) 瞬間歸位 (無動畫)。children('li:first').appendTo(this) 將第一個 li 移到 ul 末尾,實現無縫循環。setInterval 定時觸發,配合 hover 清除/恢復定時器,提升使用者體驗。// 初始化時複製前 N 項到尾部
var $items = $ul.children().clone();
$ul.append($items);
// 滾動至複製區開頭時,瞬間跳回原始區開頭 (marginTop=0)
// 需配合 position:relative + left 動畫或 transform:translateY
.scroll-box { height: 90px; } /* 3 * 30px */
$ul.animate({marginTop: -liHeight}, 500, function() {
$(this).css('marginTop', 0).children('li:first').appendTo(this);
});
.scroll-box { white-space: nowrap; overflow: hidden; }
$ul.animate({marginLeft: -itemWidth}, 500, function() {
$(this).css('marginLeft', 0).children('li:first').appendTo(this);
});
@keyframes scrollUp {
0% { transform: translateY(0); }
100% { transform: translateY(-120px); } /* 4項 * 30px */
}
.scroll-box ul {
animation: scrollUp 12s linear infinite;
/* 滑鼠懸停暫停 */
}
.scroll-box ul:hover { animation-play-state: paused; }
優點:零 JS、主執行緒零負擔、流暢度最高。缺點:項目數固定、動態增減需重算 keyframes、互動控制較難。
aria-live="polite" 區域)。