removeClass不工作

时间:2015-10-08 11:50:37

标签: jquery html scrolltop

removeClass超过200px时,我想scrolltop



$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  console.log(scroll);
  if (scroll >= 100 || scroll <= 200) {
    $(".clearHeader").addClass("darkHeader");
  } else {
    $(".clearHeader").removeClass("darkHeader");
  }
});
&#13;
.clearHeader {
  height: 200px;
  background-color: rgba(107, 107, 107, 0.66);
  position: fixed;
  top: 200;
  width: 100%;
}
.darkHeader {
  height: 100px;
}
.wrapper {
  height: 2000px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<header class="clearHeader">
</header>

<div class="wrapper">
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:6)

您需要使用&&代替||

if(scroll >= 100 && scroll <= 200)
    $(".clearHeader").addClass("darkHeader");
}
else{
    $(".clearHeader").removeClass("darkHeader");
}

使用toogleClass()

也可以实现
$(".clearHeader").toggleClass("darkHeader", scroll >= 100 && scroll <= 200);

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  $(".clearHeader").toggleClass("darkHeader", scroll >= 100 && scroll <= 200);
});
.clearHeader {
  height: 200px;
  background-color: rgba(107, 107, 107, 0.66);
  position: fixed;
  top: 200;
  width: 100%;
}
.darkHeader {
  height: 100px;
}
.wrapper {
  height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<header class="clearHeader">
</header>

<div class="wrapper">
</div>

答案 1 :(得分:1)

1-请始终使用toggleClass()而不是删除和添加...它需要更少的内存+更少的代码... http://api.jquery.com/toggleclass/

2-如果您想在特定条件下做某事,请始终使用&#34;&amp;&amp;&#34; ..这说明了它的工作原理: &安培;&安培; http://www.w3schools.com/js/tryit.asp?filename=tryjs_comparison_and