Scrolling sticky header jumping

后端 未结 1 1539
栀梦
栀梦 2020-12-16 00:29

I\'m creating a header that\'ll stick in place when the user scrolls down past a set amount of pixels. My header is 121 pixels high, but the part of the header I want to sti

相关标签:
1条回答
  • 2020-12-16 01:03

    Here is the problem:

    When the header has a "static" positioning, it pushes the content down so it does not overlap with it. When the positioning changes from "static" to "fixed", it no longer cares whether it overlaps with the content so the content "jumps up" to the top of the page because it thinks there is nothing in it's way.

    There are multiple fixes to this problem:

    The easiest one is probably to add another element that essentially takes up the space that the header did when the positioning changes.

    I did this by changing the display of the element to "block" when the header is "fixed" and "none" when the header is "static"

    Here is an updated JSFiddle: http://jsfiddle.net/6kPzW/2/

    HTML Code:

    <div id="header">header</div>
    <div id="header_placeholder"></div>
    <div id="content">Content</div>
    

    CSS Code:

    body {
        margin: 0;
        padding: 0;
    }
    #header {
        width: 100%;
        height: 121px;
        background: url(http://libertyeaglearms.com/dev/admin/graphics/header-bg.png);
    }
    #content {
        margin: 10px auto;
        width: 300px;
        min-height: 600px;
    }
    #header_placeholder {
        height:121px;
        width:100%;
        display:none;
    }
    

    JQuery Code:

    $(window).scroll(function()
    {
        if( $(window).scrollTop() > 79 )
    {
            $('#header').css({position: 'fixed'});
            $('#header_placeholder').css({display: 'block'});
    } 
    else 
    {
            $('#header').css({position: 'static', top: '-79px'});
            $('#header_placeholder').css({display: 'none'});
    }
    });
    
    0 讨论(0)
提交回复
热议问题