经过滚动后,将Div置于顶部 [英] Sticking Div to Top After Scrolling Past it
问题描述
现在,我可以在向下滚动 320px
后将 div
想知道是否有另一种方法来实现这一点。下面我有我的代码:
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:
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();
});
它可以工作,但上面有一些 divs
将不会总是相同的高度,所以我不能依赖 320px
。我如何让这个工作,而不使用 if($(window).scrollTop()> 320)
所以我可以让它淡入在用户滚动过 div #navwrap
?
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
?
推荐答案
元素的<$ c> c $ c> offset()。top 。这样,元素将从文档中的开始位置固定,而不管它在哪里。例如:
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:
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);
这篇关于经过滚动后,将Div置于顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!