Keep Side Navigation Fixed with Scrolling of page

2020-05-28 11:38发布

问题:

I have a clients website - www.stagecraft.co.uk and they want the navigation on the hire pages (longer page) to still be there at when you scroll the page down. I've had a quick go (not live) with position fixed but in doing so it the leftside navigation is about 200px or so from the top of the window. Any when to get it at the top of the window when scrolling?

Thanks in advance....

回答1:

You could make it position fixed, only when scrolling has reached a certain point:

$(window).scroll(function() {
    if ($(this).scrollTop() > 200) { //I just used 200 for testing
        $("#tester").css({ "position": "fixed", "top": 0 });
    } else {
        $("#tester").css({ "position": "absolute", "top": "200px" }); //same here
    }               
});

and the CSS for the div is as following:

#tester {
    position: absolute;
    right: 20px;
    top: 200px;
    height: 200px;
    width: 100px;
    background: red;
}


回答2:

$(window).scroll(function() { $('#myElement').css('top', $(this).scrollTop() + "px"); });

I got this from question 257250

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?



回答3:

I would hesitate to use only jquery - I think it's really annoying when scrolling a page and a DIV "jumps" due to javascript updating the position of an element.

I'd use position:fixed, and just move the position of the box to the top of the left side with javascript when scrolling down initially, and then leave it there. It's a sort of compromise.