Position fixed when scrolled passed certain amount of pixels

前端 未结 5 1853
傲寒
傲寒 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: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/

提交回复
热议问题