javascript 当窗口顶部到达特定元素时将类添加到 DIV 并在未到达时将其删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20314061/
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
Add a class to a DIV when top of the window reach a specific element and remove it when not
提问by Farzad Bayan
I have a .navigation
in the top of the wrapper.
I want to add it a .fixed
class, when the top of the window reached the .bottom
DIV & remove this class when the top of the .bottom
is in the window`s scope (it's a toggling between add and remove .fixed class).
我.navigation
在包装纸的顶部有一个。我想给它添加一个.fixed
类,当窗口顶部到达.bottom
DIV时,当顶部在窗口.bottom
的范围内时删除这个类(这是在添加和删除 .fixed 类之间切换)。
<div id="wrapper">
<div class="navigation">
<!-- There are some list elements here -->
</div>
<div class="bottom"></div>
</div>
It's what I made, but not work
这是我做的,但不起作用
bottom = $('.bottom');
$(window).scroll(function(){
if ($(this).scrollTop() > bottom){
$('.navigation').addClass('fixed');
}
else{
$('.navigation').removeClass('fixed');
}
});
回答by Labu
var bottom = $('.bottom').offset().top;
var bottom = $('.bottom').offset().top;
That should do it.
那应该这样做。
This compares the offset from the top of the viewport to the window's scrollTop()
instead of comparing a whole element.
这将比较从视口顶部到窗口的偏移量,scrollTop()
而不是比较整个元素。