我需要实现在窗口滚动到末尾之前 float 在同一位置的内容上然后粘到内容末尾的按钮。
换句话说,元素作为relative
直到它到达指定的位置。从此位置开始,行为更改为 fixed
。
所以我正在寻找一种 css 方法来做到这一点。或者 javascript 解决方案,如果样式表不可能的话。
预期结果:
当内容 block 在指定位置下时:
当它到达终点时,初始位置低于它的底边:
最佳答案
对于现代浏览器,您可以使用 position: sticky
在到达顶部(或底部)时粘住。
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.
阅读更多 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>
支持的浏览器(source):
不幸的是,这个没有明确的规范 - 该功能刚刚登陆 Webkit 并且存在一些已知问题。但是对于按钮来说效果很好
关于javascript - 当页面滚动到末尾时停留在内容下方的粘性按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46305571/