jQuery on scroll toggle between two classes

2019-05-23 21:46发布

问题:

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 ?

回答1:

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

if ($(window).scrollTop() > 100){
    $('.navigation').addClass( "blue");
}
else {
    $('.navigation').removeClass("blue");
}


回答2:

Try the following code:

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

Here's the example in jsbin



回答3:

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



回答4:

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!



回答5:

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