toggleClass in jQuery skips css rule

问题: I have a div of id="header" with initial css rule: padding: 25px 0;. When scrolling down the page, I want to decrease this div's padding: $(document).ready(function() {...

问题:

I have a div of id="header" with initial css rule: padding: 25px 0;. When scrolling down the page, I want to decrease this div's padding:

$(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;
}

However when I scroll down the page, padding does not change. What is wrong with my code?


回答1:

Your two conditions are cancelling each other out. It makes more sense to make a single call to toggleClass() and provide the boolean argument to specify if the class should be added or removed based on the current scrollTop value. Also note that you should listen for the scroll on the window instead of the document. Try this:

$(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>


回答2:

Use the .scroll() method on window, not this or the document. Additionally, it may be easier to use .addClass() and .removeClass() in this case.

$(document).ready(function() {

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

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

});
  • 发表于 2019-04-01 21:01
  • 阅读 ( 156 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除