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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:13:27  来源:igfitidea点击:

Add a class to a DIV when top of the window reach a specific element and remove it when not

javascriptjqueryhtmlcss

提问by Farzad Bayan

I have a .navigationin the top of the wrapper. I want to add it a .fixedclass, when the top of the window reached the .bottomDIV & remove this class when the top of the .bottomis in the window`s scope (it's a toggling between add and remove .fixed class).

.navigation在包装纸的顶部有一个。我想给它添加一个.fixed类,当窗口顶部到达.bottomDIV时,当顶部在窗口.bottom的范围内时删除这个类(这是在添加和删除 .fixed 类之间切换)。

add fixed class to the navigation

向导航添加固定类

<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()而不是比较整个元素。