简体   繁体   中英

Sticky button that stay below the content when the page is scrolled to the end

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:

在页面底部

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 compatible 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.net/t7j726c1/

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

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