简体   繁体   中英

Navbar makes content jump when position is changed to fixed on scroll past

I've been trying to make my navbar stick to top when I scroll by it and achieved it. The only problem is that my content kind of kicks up when the navbar transition to position fixed is executed.

Here is an example of this behavior: http://jsfiddle.net/7HHa5/4/

JavaScript

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

I am using bootstrap and jQuery.

How can I avoid this behavior?

When you set the header to position: absolute , it leaves an empty space which gets filled by the content. You need to add a margin to the top of the content when the header becomes fixed, like this:

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    var content = document.getElementById("content");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
        content.style.marginTop = '55px'
    } else {
        header.style.position = "";
        header.style.top = "";
        content.style.marginTop = '0'
    }
}

See http://jsfiddle.net/2EhLs/1/ for an example.

However, there is a better way.

Since you are already using Bootstrap, you should consider using the built-in Affix feature.

The best example is this one from another question :

$('#nav-wrapper').height($("#nav").height());

$('#nav').affix({
    offset: { top: $('#nav').offset().top }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM