DIV CSS 佈局教程網

jQuery 固定浮動側邊欄:滾動時讓側欄黏在視窗上
編輯:JavaScript綜合知識     

這個效果現在很常見:頁面很長,當捲軸往下拖到某個位置後,側邊欄會脫離原本的位置,固定跟著視窗移動,方便使用者隨時操作。實作思路是:先取得該元素距離頁面頂部的距離,接著監聽捲動,當捲動距離超過該值時就加上 fixed 定位。

HTML 結構

<div id="header">header</div>
<div id="sidebarWrap">
    <div id="sidebar">Sidebar</div>
</div>
<div id="main">Main</div>
<div id="footer">footer</div>

外層多包一個 sidebarWrap 是有原因的:側欄一旦變成 fixed,就脫離了正常的文件流,原本撐開的高度會塌陷。由外層容器保留佔位,版面才不會跳動。

CSS

body {
    margin: 10px auto;
    font-family: sans-serif;
    width: 500px;
}
div {
    border-radius: 5px;
    box-shadow: 1px 2px 5px rgba(0,0,0,0.3);
    border: 1px solid #ccc;
    padding: 5px;
}
#sidebarWrap {
    height: 400px;
    width: 210px;
    float: right;
    position: relative;
    box-shadow: none;
    border: none;
    margin: 0;
    padding: 0;
}
#main {
    width: 270px;
    height: 4000px;
}
#footer {
    clear: both;
    margin: 10px 0;
    height: 600px;
}
#sidebar {
    width: 200px;
    height: 300px;
    position: absolute;
}
#header {
    height: 200px;
    margin-bottom: 10px;
}
#sidebar.fixed {
    position: fixed;
    top: 0;
}

JavaScript

$(function() {
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0));

    var maxY = footTop - $('#sidebar').outerHeight();

    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        if (y > top) {
            if (y < maxY) {
                $('#sidebar').addClass('fixed').removeAttr('style');
            } else {
                $('#sidebar').removeClass('fixed').css({
                    position: 'absolute',
                    top: (maxY - top) + 'px'
                });
            }
        } else {
            $('#sidebar').removeClass('fixed');
        }
    });
});

三個狀態說明

  1. y 小於 top:還沒捲到,側欄維持原本的絕對定位,乖乖待在容器裡。
  2. top 到 maxY 之間:加上 fixed,側欄黏在視窗頂端隨捲動移動。
  3. y 超過 maxY:已經接近頁尾,改回絕對定位並指定 top,讓側欄停在footer之前,不會壓到頁尾內容。

maxY 的算法是「footer 頂端減去側欄高度」,也就是側欄在不侵入頁尾的前提下能到的最遠位置。

實作上值得注意的一點:scroll 事件觸發非常頻繁,這個範例每次都做讀取樣式與 class 操作,在複雜頁面裡可能造成卡頓。實務上可以搭配 requestAnimationFrame 或節流(throttle)處理,並把 $('#sidebar') 存成變數避免重複查詢。此外,如今也可以純用 CSS 的 position: sticky 達到類似效果,程式碼少很多,只是頁尾那段的「不越界」行為需要用容器高度來約束。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved