萬盛學電腦網

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

jQuery 滾動特效大全:單行、多行、翻屏、可控滾動完整實現

滾動公告/列表:經典 UI 組件

垂直滾動公告、跑馬燈、消息流等場景廣泛存在。本文匯總四種主流 jQuery 滾動實現,從簡單到複雜,滿足不同業務需求。

方案一:單行無縫滾動(最基礎)

核心原理

  1. 容器固定高度、overflow: hidden
  2. 動畫將 ul 上移一行高度
  3. 動畫完成後,將第一個 li 移到末尾,重置 margin-top
  4. 循環定時器

完整代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>單行滾動</title>
<style>
#scrollDiv { width: 300px; height: 25px; line-height: 25px; border: 1px solid #ccc; overflow: hidden; }
#scrollDiv li { height: 25px; padding-left: 10px; list-style: none; }
</style>
</head>
<body>
<div id="scrollDiv">
    <ul>
        <li>百度 www.baidu.com</li>
        <li>腳本之家 www.jb51.net</li>
        <li>這是公告標題的第三行</li>
        <li>這是公告標題的第四行</li>
        <li>這是公告標題的第五行</li>
        <li>這是公告標題的第六行</li>
        <li>這是公告標題的第七行</li>
        <li>這是公告標題的第八行</li>
    </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
function AutoScroll(obj) {
    $(obj).find("ul:first").animate({
        marginTop: "-25px" // 一行高度
    }, 500, function() {
        $(this).css({ marginTop: "0px" }).find("li:first").appendTo(this);
    });
}

$(function() {
    setInterval(function() { AutoScroll("#scrollDiv"); }, 1000);
});
</script>
</body>
</html>

方案二:多行滾動插件化(可配置行數、速度、間隔)

插件模式封裝

(function($) {
    $.fn.extend({
        Scroll: function(opt, callback) {
            if (!opt) var opt = {};
            var _this = this.eq(0).find("ul:first");
            var lineH = _this.find("li:first").height();        // 行高
            var line = opt.line ? parseInt(opt.line, 10) : parseInt(this.height() / lineH, 10); // 每次滾動行數
            var speed = opt.speed ? parseInt(opt.speed, 10) : 500;  // 動畫速度
            var timer = opt.timer ? parseInt(opt.timer, 10) : 3000; // 間隔時間
            
            if (line == 0) line = 1;
            var upHeight = 0 - line * lineH;
            
            var scrollUp = function() {
                _this.animate({ marginTop: upHeight }, speed, function() {
                    for (var i = 1; i <= line; i++) {
                        _this.find("li:first").appendTo(_this);
                    }
                    _this.css({ marginTop: 0 });
                });
            };
            
            // 懸停暫停
            var timerID = setInterval(scrollUp, timer);
            _this.hover(
                function() { clearInterval(timerID); },
                function() { timerID = setInterval(scrollUp, timer); }
            ).mouseout(); // 觸發一次 mouseout 初始化
            
            return this; // 鏈式調用
        }
    });
})(jQuery);

// 使用
$(function() {
    $("#scrollDiv").Scroll({ line: 4, speed: 500, timer: 1000 });
});

HTML 結構(同單行,只需調整容器高度)

<div id="scrollDiv" style="height: 100px;"> ... </div>

方案三:可控雙向滾動(上/下按鈕控制)

<style>
#scrollBox { width: 300px; height: 100px; border: 1px solid #ccc; overflow: hidden; position: relative; }
#scrollList { position: absolute; left: 0; top: 0; list-style: none; margin: 0; padding: 0; }
#scrollList li { height: 25px; line-height: 25px; padding-left: 10px; }
.controls { margin-top: 10px; text-align: center; }
.controls button { margin: 0 5px; padding: 5px 15px; cursor: pointer; }
</style>

<div id="scrollBox">
    <ul id="scrollList">
        <li>第 1 條消息</li> ... <li>第 10 條消息</li>
    </ul>
</div>
<div class="controls">
    <button id="btnUp">向上</button>
    <button id="btnDown">向下</button>
    <button id="btnStop">停止</button>
    <button id="btnStart">開始</button>
</div>

<script>
$(function() {
    var $list = $("#scrollList");
    var $box = $("#scrollBox");
    var lineH = $list.find("li:first").height();
    var visibleLines = Math.floor($box.height() / lineH);
    var timer = null;
    var isAuto = true;

    function scrollUp() {
        $list.animate({ marginTop: -lineH }, 300, function() {
            $list.find("li:first").appendTo($list);
            $list.css({ marginTop: 0 });
        });
    }
    function scrollDown() {
        $list.find("li:last").prependTo($list);
        $list.css({ marginTop: -lineH });
        $list.animate({ marginTop: 0 }, 300);
    }

    function startAuto() {
        if (timer) return;
        timer = setInterval(scrollUp, 2000);
    }
    function stopAuto() {
        clearInterval(timer);
        timer = null;
    }

    $("#btnUp").click(function() { scrollUp(); stopAuto(); });
    $("#btnDown").click(function() { scrollDown(); stopAuto(); });
    $("#btnStop").click(stopAuto);
    $("#btnStart").click(startAuto);

    $box.hover(stopAuto, startAuto);
    startAuto();
});
</script>

方案四:圖片/內容翻屏滾動(全屏輪播)

<style>
.fullpage { width: 100%; height: 100vh; overflow: hidden; position: relative; }
.screen { width: 100%; height: 100%; position: absolute; top: 0; left: 0; transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1); }
.screen.active { transform: translateY(0); }
.screen.next { transform: translateY(100%); }
.screen.prev { transform: translateY(-100%); }
.nav { position: fixed; right: 20px; top: 50%; transform: translateY(-50%); z-index: 10; }
.nav button { display: block; margin: 5px 0; padding: 8px 12px; background: rgba(0,0,0,0.5); color: #fff; border: none; border-radius: 4px; cursor: pointer; }
</style>

<div class="fullpage" id="fullpage">
    <div class="screen active" style="background: #e3f2fd;"><h1>第一屏</h1></div>
    <div class="screen next" style="background: #fff3e0;"><h1>第二屏</h1></div>
    <div class="screen next" style="background: #e8f5e9;"><h1>第三屏</h1></div>
    <div class="screen next" style="background: #fce4ec;"><h1>第四屏</h1></div>
</div>
<div class="nav">
    <button data-dir="up">上一屏</button>
    <button data-dir="down">下一屏</button>
</div>

<script>
$(function() {
    var $screens = $(".screen");
    var current = 0;
    var animating = false;

    function goTo(index, dir) {
        if (animating || index < 0 || index >= $screens.length) return;
        animating = true;
        
        $screens.removeClass("active next prev");
        $screens.eq(current).addClass(dir === "up" ? "prev" : "next");
        $screens.eq(index).addClass("active");
        current = index;
        
        setTimeout(function() { animating = false; }, 500);
    }

    $(".nav button").click(function() {
        var dir = $(this).data("dir");
        goTo(current + (dir === "up" ? -1 : 1), dir);
    });

    // 鍵盤/滾輪支持
    $(document).on("keydown", function(e) {
        if (e.key === "ArrowUp") goTo(current - 1, "up");
        if (e.key === "ArrowDown") goTo(current + 1, "down");
    });

    var wheelTimer;
    $(window).on("wheel", function(e) {
        clearTimeout(wheelTimer);
        wheelTimer = setTimeout(function() {
            goTo(current + (e.originalEvent.deltaY > 0 ? 1 : -1), e.originalEvent.deltaY > 0 ? "down" : "up");
        }, 50);
    });
});
</script>

性能優化與最佳實踐

優化點建議
DOM 操作最小化使用 appendTo/prependTo 移動現有節點,而非重建
動畫隊列管理使用 .stop(true, true) 防止快速點擊疊加動畫
請求動畫幀複雜動畫考慮 requestAnimationFrame 或 CSS transition
內存洩漏防範銷毀組件時清除 setInterval/setTimeout、解綁事件
GPU 加速滾動容器添加 transform: translateZ(0) 或 will-change: transform

無障礙與用戶體驗

  • 提供暫停/播放控制
  • 滾動速度適中,文字可讀
  • 鍵盤可操作(方向鍵、空格暫停)
  • 減少動畫偏好:@media (prefers-reduced-motion: reduce) 禁用動畫

總結

從簡單的單行跑馬燈到複雜的全屏翻頁,jQuery 滾動特效的核心都是「DOM 位置操作 + 定時器/動畫」。掌握 animate、appendTo/prependTo、margin-top 重置等核心技巧,並封裝為可配置插件,能應對絕大多數滾動展示需求。現代項目中,CSS animation/transition + transform 往往性能更優,建議優先考慮純 CSS 方案,JS 僅處理邏輯控制。

copyright © 萬盛學電腦網 all rights reserved