admin管理员组

文章数量:1422254

I need to implement the button that floats over the content on the same position before the window is scrolled to the end and then sticks to the end of content.

In other words, the element acted as relative till it reaches specified position. Starting from this position behavior changed as fixed.

So I'm searching for a css way to do this. Or javascript solution, if it's not possible with stylesheet.

Expected result:

When the content block is under specified position:

And when it reaches the end so initial position is below the its bottom edge:

I need to implement the button that floats over the content on the same position before the window is scrolled to the end and then sticks to the end of content.

In other words, the element acted as relative till it reaches specified position. Starting from this position behavior changed as fixed.

So I'm searching for a css way to do this. Or javascript solution, if it's not possible with stylesheet.

Expected result:

When the content block is under specified position:

And when it reaches the end so initial position is below the its bottom edge:

Share Improve this question asked Sep 19, 2017 at 16:33 Oleh RybalchenkoOleh Rybalchenko 8,0894 gold badges26 silver badges40 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

For modern browsers you can use position: sticky to stick when it reaches the top (or bottom).

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.

Read more in this MDN article.

.sticky-button {
  position: sticky;
  position: -webkit-sticky;
  position: -moz-sticky;
  position: -ms-sticky;
  position: -o-sticky;
  bottom: 10px;
}
<div style='width: 500px; height: 3000px; background: #ffffcc; padding: 20px'>
  <div style='width: 500px; height: 2000px; background: #eeffff; padding: 20px'>
    Page content
  </div>
  <button class='sticky-button'>Load more...</button>
</div>

Browsers supporting (source):

Unfortunately, there isn't a clear spec for this one - the feature is just landed on Webkit and there are some known issues. But for buttons it works well

Try to google for a library that does this.

The concept is easy, but hard to make it patible with all the browsers.

You will need to know:

1.element's height:

element.style.height

2.window height:

window.innerHeight

3.window scroll pos:

document.body.scrollTop

That should be all the parameters you need.

Here is a quick fiddle I just made:

https://jsfiddle/t7j726c1/

Again, I would try to find a library to do this.

本文标签: javascriptSticky button that stay below the content when the page is scrolled to the endStack Overflow