当窗口顶部到达特定元素时,向DIV添加类,否则删除它 [英] Add a class to a DIV when top of the window reach a specific element and remove it when not
本文介绍了当窗口顶部到达特定元素时,向DIV添加类,否则删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在包装器顶部有一个 .navigation
。
我想添加一个 .fixed
类,当窗口的顶部到达 .bottom
DIV&当 .bottom
的顶部在窗口的范围内时(它是在添加和删除.fixed类之间切换),删除此类。
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).
<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');
}
});
推荐答案
var bottom = $ '.bottom')。offset()。top;
这样就可以了。
这会比较从视口顶部到窗口 scrollTop()
的偏移量,而不是比较整个元素。
This compares the offset from the top of the viewport to the window's scrollTop()
instead of comparing a whole element.
这篇关于当窗口顶部到达特定元素时,向DIV添加类,否则删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文