jQuery on scroll toggle between two classes

2019-05-23 21:07发布

By default I have a navigation bar which has a red background color.

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.

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.

Here is my attempt :

$(document).ready(function(){
  $(window).scroll(function(){
    if ($(window).scrollTop() > 100){
        $('.navigation').toggleClass( "blue");
    }
 });
});

But this is not working. Here's a jsbin.

Any ideas how to get it to work ?

5条回答
The star\"
2楼-- · 2019-05-23 21:45

The problem is that you call toggleClass everytime the user scrolls. This code would fix this issue:

$(document).ready(function(){
    $(window).scroll(function(){
        if ($(window).scrollTop() > 100 && !$( ".navigation" ).hasClass( "blue" ) || $(window).scrollTop() === 0 && $( ".navigation" ).hasClass( "blue" ){
            $('.navigation').toggleClass( "blue");
        }

    });
});

The jsbin

查看更多
Summer. ? 凉城
3楼-- · 2019-05-23 21:46

Using toggleClass() may be the wrong solution for this. Use addClass/removeClass instead:

if ($(window).scrollTop() > 100){
    $('.navigation').addClass( "blue");
}
else {
    $('.navigation').removeClass("blue");
}
查看更多
Emotional °昔
4楼-- · 2019-05-23 21:46

Try the following code:

$(document).ready(function () {
    $(window).scroll(function () {
        $('.navigation').toggleClass("blue", ($(window).scrollTop() > 100));
     });
});

Here's the example in jsbin

查看更多
smile是对你的礼貌
5楼-- · 2019-05-23 21:54

You can use .addClass() and removeClass()like this one: http://jsfiddle.net/csdtesting/qhfmw8hx/

$(window).scroll(function() {
  var windowYmax = 100;
  var scrolledY = $(window).scrollTop();

  if (scrolledY > windowYmax) {

    $('.navigation').addClass("blue");
  } else {
    $('.navigation').removeClass("blue");
    $('.navigation').addClass("red");
  }
});
.navigation {
  height: 800px;
}
.navigation.red {
  background: red;
}
.navigation.blue {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navigation red">scroll me down and up please to see me changing colors...</div>

Hope it helps!

查看更多
萌系小妹纸
6楼-- · 2019-05-23 22:06

You're working with adding a class and removing another, i would suggest just using addClass and removeClass for this case. Also you can chain the methods.

$(document).ready(function(){
  $(window).scroll(function(){
    if ($(window).scrollTop() > 100){
      $('.navigation').addClass('blue').removeClass('red');
    } else {
      $('.navigation').addClass('red').removeClass('blue');
    }
  });
});

Here's the jsbin

查看更多
登录 后发表回答