javascript 如何使固定浮动元素停在#footer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6701988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make fixed floating element stop at #footer?
提问by Mike Stevenson
Below is the code I am using to fix a sidebar as the user scrolls. As of now, it overlaps with my footer. How can I make it stop at a certain point or when it hits the footer?
下面是我用来在用户滚动时修复侧边栏的代码。截至目前,它与我的页脚重叠。我怎样才能让它在某个点或当它碰到页脚时停止?
<script type="text/javascript">
$(document).ready(function() {
if ($('.pageheaderwrap').length) {
$(window).scroll(function() {
if ($(this).scrollTop() > 362) {
$(".sidebar-left").css({
"position": "fixed",
"top": 0
});
} else {
$(".sidebar-left").css({
"position": "absolute",
"top": "255px"
});
}
});
} else {
$(window).scroll(function() {
if ($(this).scrollTop() > 230) {
$(".sidebar-left").css({
"position": "fixed",
"top": 0
});
} else {
$(".sidebar-left").css({
"position": "absolute",
"top": "125px"
});
}
});
}
});
</script>
回答by bigspotteddog
Here is something that might work for you:
这里有一些可能对你有用的东西:
The jquery plugin that is doing this sets elements fixed whatever margin from the top of the page. With an optional limit, it will unfix the element and have it continue to scroll up the page, keeping it away from your footer. You would set the limit to the top of your footer, plus the height of whatever your target element is.
执行此操作的 jquery 插件设置元素固定页面顶部的任何边距。使用可选限制,它将取消固定元素并让它继续向上滚动页面,使其远离页脚。您可以将限制设置为页脚的顶部,加上目标元素的高度。
Here is the code usage for this scenario (the fiddle above):
这是此场景的代码用法(上面的小提琴):
$(document).ready(function() {
$('#cart').scrollToFixed({
marginTop: 10,
limit: $('#footer').offset().top
});
});
Here is the link to the plugin and its source:
这是插件及其来源的链接:
回答by Adam
Why not eliminate all the javascript and do it with CSS:
为什么不消除所有的 javascript 并使用 CSS 来实现:
.sidebar-left {
position: fixed;
bottom: 20px; /* height of your footer */
}
回答by Majid Eltayeb
I see the easiest way to reach this is to use position: sticky;
instead of position: fixed;
and give the parent of this section position: relative;
to keep the sticky container within the parent container borders.
我认为达到此目的的最简单方法是使用position: sticky;
而不是position: fixed;
并提供此部分的父级,position: relative;
以将粘性容器保持在父级容器边界内。