简体   繁体   中英

How to make a div stick to top or bottom, depending on how the user is scrolling?

Hello. I know there are a lot of questions about sticking a div to top or bottom when scrolling, but my problem is more specific.

The problem is that I want the div to stick to the top or the bottom, depending on how the user scrolls.

I made this jsFiddle snippet to show how the content is set up: https://jsfiddle.net/DTcHh/6155/ .

The result I want is: whenever the user is scrolling, the content on the side should also scroll at the same time with the other content. If the content on the side reached the end (top or bottom), then it should stick to the top or bottom (depending on where the end of the content is reached)

For example, in the snippet I provided, I want the content on the side to scroll until the "Fixed content Last." is visible, then stick to the bottom as the user scrolls down. Now, if the user scrolls up, I want the side content to also scroll up until "Fixed content First." is visible, then stick to the top.

Html of the side contnet:

<nav >
      <div id="filterAnchor"></div>
      <div id="filterScroll" class="fixed_div">
          Fixed content First.</br>
          Fixed content.</br>
          Fixed content.</br>
          ...
          [more "Fixed content."]
          ...
          Fixed content.</br>
          Fixed content.</br>
          Fixed content Last.</br>
      </div>
</nav>

In the first place you need to know the scroll direction. And if I'm right you want the sticky side bar to scroll with the content but never out of sight.

I've edited the fiddle to do this.

It should need some optimization but I hope you get the idea. The tricky part is to check if the bottom is reached and I'm still not sure if this is the right way:

if ($window.height() <= $filterClass.height() + top) {
    $filterClass.addClass('stick-bottom');
    $filterClass.css('top', '');
}

Edit (see comments for more context):

With this updated fiddle I added support for different situations:

1. When the side content is longer than main content:
The default position is absolute. No javascript is needed for this to work properly.

2. When the side content is longer than the window height:
The position is set to fixed. When scrolling down (content moves up) the side sticks to the bottom when reached:

// top means position top of the fixed side
if(top < 0 && fixedHeight + top < windowHeight) {
    $filterClass.addClass('stick-bottom');
    $filterClass.css('top', '');
} else {
    $filterClass.css('top', top+diff);
}

3. When the side content is shorter than the window height:
The position is set to fixed. Situation as in original answer above.

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