javascript 滚动过去后将 Div 粘贴到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10789936/
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
Sticking Div to Top After Scrolling Past it
提问by Joe Bobby
Right now, I'm able to stick the div
to the top after it scrolls down 320px
but I wanted to know if there is another way of achieving this. Below I have my code:
现在,我可以div
在向下滚动后将其固定在顶部,320px
但我想知道是否有另一种方法可以实现这一点。下面我有我的代码:
jQuery(function($) {
function fixDiv() {
if ($(window).scrollTop() > 320) {
$('#navwrap').css({ 'position': 'fixed', 'top': '0', 'width': '100%' });
}
else {
$('#navwrap').css({ 'position': 'static', 'top': 'auto', 'width': '100%' });
}
}
$(window).scroll(fixDiv);
fix5iv();
});
it works, but some divs
above it will not always be the same height so I can't rely on the 320px
. How do I get this to work without using if ($(window).scrollTop() > 320)
so I can get it to fade in at the top after the user scrolls past the div #navwrap
?
它有效,但divs
它上面的一些并不总是相同的高度,所以我不能依赖320px
. 如何在不使用的情况下使其工作,if ($(window).scrollTop() > 320)
以便在用户滚动到div #navwrap
?
回答by Rory McCrossan
Try using the offset().top
of the #navwrap
element. That way the element will be fixed from it's starting position in the document, regardless of where that is. For example:
尝试使用offset().top
的的#navwrap
元素。这样元素就会从它在文档中的起始位置开始固定,不管它在哪里。例如:
function fixDiv() {
var $div = $("#navwrap");
if ($(window).scrollTop() > $div.data("top")) {
$div.css({'position': 'fixed', 'top': '0', 'width': '100%'});
}
else {
$div.css({'position': 'static', 'top': 'auto', 'width': '100%'});
}
}
$("#navwrap").data("top", $("#navwrap").offset().top); // set original position on load
$(window).scroll(fixDiv);