萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現單行文字間歇向上滾動跑馬燈:極簡代碼、自動循環、無縫銜接

完整可執行範例

<!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>

核心邏輯拆解

  1. animate({marginTop: -liHeight}):向上移動一個 li 高度。
  2. complete 回調中:
    • css('marginTop', 0) 瞬間歸位 (無動畫)。
    • children('li:first').appendTo(this) 將第一個 li 移到 ul 末尾,實現無縫循環。
  3. setInterval 定時觸發,配合 hover 清除/恢復定時器,提升使用者體驗。

進階變體

無縫滾動 (複製首尾項)

// 初始化時複製前 N 項到尾部
var $items = $ul.children().clone();
$ul.append($items);
// 滾動至複製區開頭時,瞬間跳回原始區開頭 (marginTop=0)
// 需配合 position:relative + left 動畫或 transform:translateY

多行顯示 (顯示 3 行,每次滾 1 行)

.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);
});

現代 CSS Only 方案 (零 JS)

@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" 區域)。
  • 滑鼠懸停、鍵盤聚焦時暫停。
  • 確保色彩對比、字體大小可縮放。
copyright © 萬盛學電腦網 all rights reserved