简体   繁体   中英

Trouble with positioning of element with javascript

I'm trying to achieve a navigation bar which is "catched" as the user scrolls to it. I am semi achieving my goal but with my current attempt this is also moving my main content as I scroll which is not what I want to achieve. Here's what I have https://jsfiddle.net/abp1rwhp/

$(function(){
var navHeight = $('#nav-bar').offset().top;
console.log(navHeight)
$(window).on('scroll', function() {
    if(screen.width < 980) {
    }
    if($(window).scrollTop() > navHeight){
        $('#nav-bar').css({
            'top': $(window).scrollTop() > 0 ? '0px' : '0px',
            'position': 'fixed'
        })
    }
    if($(window).scrollTop() < navHeight){
        $('#nav-bar').css({
            'top': '',
            'position': 'relative'
        })
    }
});
})

As you can see the content section moves down (I think 40px) when you scroll, how would I go about fixing this issue?

Because the Nav-bar is originally relative, it pushes down the contents section. When you give it position fixed, the section goes up, because the Nav-bar no longer uses that space in the page.

To combat this, you could give the section a margin-top of 40px, when you give the nav-bar position relative, so that that 40px space is kept.

I was able to solve your problem by rewriting the CSS in your two if statements like this:

    if ($(window).scrollTop() > navHeight) {
        $('#nav-bar').css({
            'top': '0px',
            'position': 'fixed'
        });
    }

    if ($(window).scrollTop() < navHeight) {
        $('#nav-bar').css({
            'top': '80px',
            'position': 'absolute'
        });
    }

You don't want your #nav-bar to be relative because that re-inserts it into the flow of the document, pushing the contents down. In other words, it is laid out the way it would normally be and then applies any positioning from top, left, etc. after that.

Instead, I made it absolute with the position from the top (80px) it has initially when the document loads.

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