jQuery中的toggleClass跳过CSS规则

时间:2019-03-29 14:03:30

标签: jquery html css

我有一个id="header"的div,其初始CSS规则为:padding: 25px 0;。向下滚动页面时,我要减少此div的填充:

$(document).ready(function() {
  var headerID = $("#header");
  $(this).scroll(function() {
    if (!$(this).scrollTop()) 
      headerID.toggleClass("headerScrolled");
    else if (!headerID.is(".headerScrolled")) 
      headerID.toggleClass("headerScrolled");
  });
});
.headerScrolled {
  padding: 15px 0;
}

但是,当我向下滚动页面时,填充不会更改。我的代码有什么问题?

2 个答案:

答案 0 :(得分:4)

您的两个条件互相抵消。一次调用toggleClass()并提供boolean参数来指定是否应该基于当前scrollTop的值来添加或删除该类是更有意义的。另请注意,您应该听window而不是document上的滚动。试试这个:

$(document).ready(function() {
  var $header = $("#header");

  $(window).scroll(function() {
    $header.toggleClass('headerScrolled', $(this).scrollTop() !== 0);
  });
});
html,
body {
  height: 1000px;
  margin: 0;
}

#header {
  padding: 25px 0;
  background-color: #CCC;
  width: 100%;
  position: fixed;
}
#header.headerScrolled {
  padding: 15px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
  Header
</div>

答案 1 :(得分:2)

.scroll()上使用window方法,而不是thisdocument。此外,在这种情况下,使用.addClass().removeClass()可能会更容易。

$(document).ready(function() {

  var $header = $("#header");

  $(window).scroll(function() {
    if (!$(window).scrollTop()) {
      $header.addClass("headerScrolled");
    } else {
      $header.removeClass("headerScrolled");
    }
  });

});