Position fixed when scrolled passed certain amount of pixels

前端 未结 5 1801
傲寒
傲寒 2021-02-06 17:10

I\'m looking for a way to position the #header element of my page as \"Fixed\" only after having scrolled downward for about 170 pixels.

Above the header is a banner, so

相关标签:
5条回答
  • 2021-02-06 17:30

    Here is a demo of a jquery plugin that takes care of this. Similar to John's answer above, but the plugin takes the solution a bit farther.

    Demo: http://jsfiddle.net/ZczEt/

    Plugin and source: https://github.com/bigspotteddog/ScrollToFixed

    Usage:

    $(document).ready(function() {
        $('.header').scrollToFixed();
    });
    
    0 讨论(0)
  • 2021-02-06 17:42

    I think this should work: http://jsfiddle.net/Skooljester/K2mFT/. However, you'll need to define a width on your header or else it'll shrink when it becomes fixed.

    0 讨论(0)
  • 2021-02-06 17:44

    This is the general idea although you may want to fudge around with the css a bit.

    var header = $("#header");
    $(document).scroll(function(e) {
        if($(this).scrollTop() > $("#banner").height()) {
            header.css({"position" : "fixed", "top" : "0"});
        } else {
            header.css("position", "relative");
        }
    });
    
    0 讨论(0)
  • 2021-02-06 17:44

    Here's a slightly more concise version:

    var header = $('#header'),
        bannerHeight = $('#banner').height(),
        win = $(window);
    
    win.scroll(function() {
        header.css({ top: Math.max(Number(win.scrollTop() - bannerHeight), 0) });
    });
    
    0 讨论(0)
  • 2021-02-06 17:47

    You need to check for the different scroll positions:

    var $header = $('#header'),
        headerPos = $header.position().top,
        $win = $(window);
    
    $win.scroll(function() {
    
        if ( $win.scrollTop() >= headerPos) {
    
            $header.css({
                'position':'fixed',
                'top':0,
                'width': '100%'
            });
    
        }
    
        if ( $win.scrollTop() <= headerPos ) {
    
            $header.css({
                'position': 'static'
            });
    
        }
    
    });
    

    http://jsfiddle.net/DOSBeats/zEDMv/10/

    0 讨论(0)
提交回复
热议问题