开发者

Position fixed when scrolled passed certain amount of pixels

开发者 https://www.devze.com 2023-03-27 06:48 出处:网络
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.

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 when people scr开发者_JAVA技巧oll down, I would like the banner to scroll away, the header to stay fixed when it hits the top of the window, and the page content to scroll underneath the header.

http://jsfiddle.net/tdskate/zEDMv/


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");
    }
});


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/


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) });
});


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();
});


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

精彩评论

暂无评论...
验证码 换一张
取 消