How to make div follow scrolling smoothly with jQuery?

后端 未结 10 2359
我寻月下人不归
我寻月下人不归 2020-11-28 19:24

In my container there are sections/boxes, but the last one of these boxes should follow scrolling when none of the other boxes are visible.

So, when user sc

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 19:49

    I wrote a relatively simple answer for this.

    I have a table that's using one of the "sticky table header" plugins to stick right below a particular div on my page, but the menu to the left of the table didn't stick (as it's not part of the table.)

    For my purposes, I knew the div that needed "stickiness" was always going to start at 385 pixels below the top of the window, so I created an empty div right above that:

    Then ran this:

    $(window).scroll(function(){   
       if ( $(window).scrollTop() > 385 ) {
        extraPadding = $(window).scrollTop() - 385;
        $('#stopMenu').css( "padding-top", extraPadding );
       } else {
         $('#stopMenu').css( "padding-top", "0" );
       }
    });
    

    As the user scrolls, it adds whatever the value of $(window).scrollTop() is to the integer 385, then adds that value to the stopMenu div that's above the thing I want to stay focused.

    In the event the user scrolls all the way back up, I just set the extra padding to 0.

    This doesn't require the user to do anything IN CSS particularly, but it's kind of a nice effect to make a small delay, so I put the class="stopMenu" in as well:

    .stopMenu {
      .transition: all 0.1s;
    }
    

提交回复
热议问题