萬盛學電腦網

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

JavaScript 滾動跟隨 (Sticky/Follow) 插件:多元素固定、底部停靠、Resize 重算完整實現

功能特色

  • 支援多個 DOM 元素同時跟隨滾動
  • 採用 CSS position: fixed 實現,效能優於 absolute + scroll 計算
  • 可設定 bottom 參數,滾動至頁尾時自動停靠,不遮擋 Footer
  • 視窗 resize 時自動重新計算參數
  • 不支援 IE6 (已淘汰),相容 IE7+ 及所有現代瀏覽器

使用方式

<script src="follow.min.js"></script>
<script>
window.onload = function() {
    var followEls = [
        document.getElementById('follow1'),
        document.getElementById('follow2')
    ];
    new Follow({
        obj: followEls,   // 單個元素或陣列
        bottom: 150       // 距離文檔底部最小像素 (對應 footer 高度)
    });
};
</script>

插件核心代碼 (Follow 類)

function Follow(options) {
    this.options = $.extend({
        obj: [],        // DOM 元素或陣列
        bottom: 0       // 底部停靠距離
    }, options);

    this.elements = Array.isArray(this.options.obj) ? this.options.obj : [this.options.obj];
    this.init();
}

Follow.prototype.init = function() {
    var self = this;
    // 1. 記錄原始位置、樣式
    this.elements.forEach(function(el) {
        el._originalStyle = {
            position: el.style.position,
            top: el.style.top,
            left: el.style.left,
            width: el.style.width,
            zIndex: el.style.zIndex
        };
        // 設定 fixed 定位所需寬度 (防止塌陷)
        el.style.width = el.offsetWidth + 'px';
    });

    // 2. 滾動事件處理 (節流)
    var ticking = false;
    function onScroll() {
        if (!ticking) {
            requestAnimationFrame(function() {
                self.updatePositions();
                ticking = false;
            });
            ticking = true;
        }
    }
    window.addEventListener('scroll', onScroll, {passive: true});

    // 3. Resize 重算
    window.addEventListener('resize', function() {
        self.elements.forEach(function(el) {
            el.style.width = el.offsetWidth + 'px'; // 更新寬度
        });
        self.updatePositions();
    });

    // 4. 初始定位
    this.updatePositions();
};

Follow.prototype.updatePositions = function() {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
    var docHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    var bottomLimit = docHeight - this.options.bottom; // 停靠臨界點

    this.elements.forEach(function(el) {
        var elHeight = el.offsetHeight;
        var elTop = el.getBoundingClientRect().top + scrollTop; // 元素原始文檔座標

        // 計算 fixed 時的 top 值
        var fixedTop = 0; // 預設貼頂
        // 若有偏移需求可從 originalStyle 計算

        // 判斷是否觸及底部停靠區
        if (scrollTop + viewportHeight > bottomLimit) {
            // 在底部區域,改為 absolute 定位固定在 bottomLimit - elHeight
            el.style.position = 'absolute';
            el.style.top = (bottomLimit - elHeight) + 'px';
        } else if (scrollTop > elTop) {
            // 已滾動超過元素原始位置,啟用 fixed
            el.style.position = 'fixed';
            el.style.top = fixedTop + 'px';
        } else {
            // 未到達,還原原始定位
            el.style.position = el._originalStyle.position;
            el.style.top = el._originalStyle.top;
            el.style.left = el._originalStyle.left;
        }
    });
};

// 掛載到全域 (或模組化導出)
window.Follow = Follow;

完整 HTML 範例

<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>JS Follow Scroll Demo</title>
<style>
html,body{margin:0;padding:0;height:2000px;}
.wrap{width:1000px;margin:0 auto;display:flex;gap:20px;}
.main{flex:1;background:#f5f5f5;padding:20px;min-height:1500px;}
.sidebar{width:300px;flex-shrink:0;}
.follow-box{background:#3498db;color:#fff;padding:20px;text-align:center;font-weight:bold;margin-bottom:20px;}
.footer{height:150px;background:#2c3e50;color:#fff;display:flex;align-items:center;justify-content:center;}
</style>
</head>
<body>
<div class="wrap">
    <div class="main">
        <h1>主內容區 (向下滾動觀察右側)</h1>
        <p>...長內容...</p>
    </div>
    <div class="sidebar">
        <div id="follow1" class="follow-box">跟隨模塊 1</div>
        <div id="follow2" class="follow-box">跟隨模塊 2</div>
    </div>
</div>
<div class="footer">Footer - 跟隨元素會停在這上方</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="follow.min.js"></script>
<script>
window.onload = function() {
    new Follow({ obj: [document.getElementById('follow1'), document.getElementById('follow2')], bottom: 150 });
};
</script>
</body>
</html>

現代化替代方案

1. CSS position: sticky (零 JS、效能最佳)

.follow-box { position: sticky; top: 0; }
.sidebar { height: fit-content; } /* 父容器需有高度約束 */

支援所有現代瀏覽器 (含 IE 無支援,但可用 Polyfill)。無法直接實現「底部停靠不遮擋 Footer」,需配合 JS 或巢狀 sticky 容器。

2. IntersectionObserver 偵測進入/離開視窗

var observer = new IntersectionObserver(function(entries) {
    entries.forEach(function(entry) {
        entry.target.classList.toggle('is-sticky', !entry.isIntersecting);
    });
}, { rootMargin: '0px 0px -150px 0px' }); // 提前 150px 觸發 (對應 bottom)

document.querySelectorAll('.follow-box').forEach(function(el) { observer.observe(el); });

配合 CSS .is-sticky { position: fixed; top: 0; } 實現,效能極佳、無 scroll 事件監聽器。

3. 成熟庫

總結

Follow 插件以 position: fixed + scroll/resize 事件實現跟隨滾動,核心邏輯在 updatePositions 計算三種狀態 (靜態、固定、底部停靠)。現代專案首選 position: sticky 或 IntersectionObserver + CSS,僅在需支援舊瀏覽器或複雜邊界條件時使用 JS 方案。

copyright © 萬盛學電腦網 all rights reserved