jQuery在两个类之间滚动切换 [英] jQuery on scroll toggle between two classes
问题描述
默认情况下,我有一个红色背景颜色的导航栏。
By default I have a navigation bar which has a red background color.
我想要做的是当用户向下滚动超过100px以更改背景时蓝色,如果他回到0px将背景改为默认状态。
What I want to do is when the users scrolls down more than 100px to change the background to blue and if he goes back to 0px to change the background to it's default state.
我想通过在两个类之间切换来做到这一点,例如< div class =navigation red>
应该是默认类,如果用户向下滚动以添加< div class =navigation blue>
如果他再次向后滚动< div class =navigation red>
。
I want to do this by toggling between two classes, for example <div class="navigation red">
should be the default class and if the user scroll down to add <div class="navigation blue">
and if he scrolls back to have <div class="navigation red">
again.
这是我的尝试:
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
$('.navigation').toggleClass( "blue");
}
});
});
但这不起作用。这是一个 jsbin 。
But this is not working. Here's a jsbin.
任何想法如何让它工作?
Any ideas how to get it to work ?
推荐答案
使用 toggleClass()
可能是错误的解决方案。请改为使用 addClass
/ removeClass
:
Using toggleClass()
may be the wrong solution for this. Use addClass
/removeClass
instead:
if ($(window).scrollTop() > 100){
$('.navigation').addClass( "blue");
}
else {
$('.navigation').removeClass("blue");
}
这篇关于jQuery在两个类之间滚动切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!