萬盛學電腦網

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

jQuery 實現滾動條固定吸頂效果

核心原理

監聽 scroll 事件,當目標元素頂部接觸視口頂部時,切換為 position: fixed; top: 0;滾動回原位置以上時恢復靜態定位。

完整實現


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>滾動吸頂效果</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <style>
        .demo { 
            border: 1px solid #dcdcdc; width: 300px; margin: 10px auto; 
            background: #fff; height: 200px; text-align: center; line-height: 200px; 
        }
        .demo.fixed {
            position: fixed; 
            top: 0; 
            left: 50%; 
            transform: translateX(-50%);
            width: 300px; 
            z-index: 1000; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            background: #2196f3; 
            color: #fff;
        }
        .spacer { height: 200px; background: #f5f5f5; margin: 10px auto; width: 300px; }
    </style>
</head>
<body>
    
1
2
3
4
我會吸頂
6
7
8
9
10

關鍵優化點

  1. 緩存原始位置:offset().top 僅計算一次
  2. 狀態標記:isFixed 避免重複操作 DOM
  3. transform 置中:left: 50%; transform: translateX(-50%) 保持水平居中
  4. 佔位元素:fixed 脫離文檔流會導致下方內容跳動,需佔位

進階:佔位元素防跳動


$(function() {
    const $sticky = $('#sticky');
    const stickyTop = $sticky.offset().top;
    const stickyHeight = $sticky.outerHeight();
    let $placeholder = null;
    let isFixed = false;
    
    $(window).on('scroll', function() {
        const scrollTop = $(this).scrollTop();
        const shouldFix = scrollTop >= stickyTop;
        
        if (shouldFix && !isFixed) {
            // 創建佔位元素保持佈局
            $placeholder = $('
').css({ height: stickyHeight, visibility: 'hidden' }); $sticky.after($placeholder); $sticky.addClass('fixed'); isFixed = true; } else if (!shouldFix && isFixed) { $placeholder?.remove(); $placeholder = null; $sticky.removeClass('fixed'); isFixed = false; } }); });

現代原生 CSS 方案


/* 瀏覽器原生支援,零 JS,性能最優 */
.sticky {
    position: sticky;
    top: 0;
    z-index: 100;
}

/* Safari 舊版需前綴 */
.sticky {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
}

✅ 支援:Chrome 56+, Firefox 32+, Safari 6.1+, Edge 16+
⚠️ 父元素 overflow: hidden/auto/scroll 會導致失效

IntersectionObserver 版本(高性能)


const sticky = document.getElementById('sticky');
const sentinel = document.createElement('div');
sentinel.style.height = '1px';
sticky.parentNode.insertBefore(sentinel, sticky);

const observer = new IntersectionObserver(([entry]) => {
    sticky.classList.toggle('fixed', entry.intersectionRatio === 0);
}, { threshold: [0, 1] });

observer.observe(sentinel);

✅ 無 scroll 事件監聽器、主線程零負擔、精確檢測

React/Vue 組件封裝


// Vue 3 StickyContainer.vue





copyright © 萬盛學電腦網 all rights reserved