简体   繁体   中英

Catch a div while scrolling to fix its position

I'm trying to have a fixed vertical navigation bar but only once the user has scrolled down to it. I have placed it 66px under my heading and it needs to get caught once the user has scrolled down to its 66px margin and stay fixed on the screen I'm close but as you can see it's not perfect. https://jsfiddle.net/1krd9zpc/7/

$(window).on('scroll', function() {
if($(window).scrollTop() > $('#navbox').offset().top){
    $('#navbox').css({
        'top': $(window).scrollTop() > 0 ? '0px' : '66px',
        'position': 'fixed'
    });
 }
});

This code (improved by Mathias W) sort of works, when we scroll back up it needs to reset to its previous position.

You have to apply the css attribute position and set it's value to fixed (position:fixed).

$(window).on('scroll', function() {
  $('#navbox').css({
      'top': $(window).scrollTop() > 0 ? '0px' : '66px',
      'position': 'fixed'
      });
});

See fiddle:

https://jsfiddle.net/3g52v5oh/

If you only want to "catch it" once you've reached the element while scrolling you can check navbox's offset position with $('#navbox').offset().top

$(window).on('scroll', function() {
    if($(window).scrollTop() > $('#navbox').offset().top){
        $('#navbox').css({
            'top': $(window).scrollTop() > 0 ? '0px' : '66px',
            'position': 'fixed'
        });
    }
});


Update for accepted answer

Save the navbox's top offset to a variable and then check if the window's scrollTop value is less or more

var navboxHeight = $('#navbox').offset().top;
$(window).on('scroll', function() {
    if($(window).scrollTop() > navboxHeight){
        $('#navbox').css({
            'top': $(window).scrollTop() > 0 ? '0px' : '66px',
            'position': 'fixed'
        });
    }
    // Reset navbox to it's default position
    if($(window).scrollTop() < navboxHeight){
        $('#navbox').css({
            'top': '',
            'position': 'static'
        });
    }
});

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