addClass removeClass不起作用

Rei*_*ara 4 html javascript css jquery twitter-bootstrap

我第一次在这里提问.我搜索了问题,但我找不到类似的问题.

我正在Brackets上建立一个带bootstrap3的企业网站.我查看是否可以使用最新版本的chrome和safari.

我正在尝试使用JQuery addClass和removeClass使我的导航栏缩小其高度并更改背景颜色,但它似乎根本不起作用.当我通过JQuery更改CSS属性时,它可以工作.我可以改变背景颜色.所以我试图通过Jquery更改多个CSS属性,它不起作用.它只允许我改变背景颜色.

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").addClass('animated-header');
    } else {
      $("#top-bar").removeClass('animated-header');
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })

}); //this is the part doesn't work

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
      $("#top-bar").css("background-color", "#ef7c7c");
    } else {
      $("#top-bar").css("background-color", "transparent");
    }
  });

  $("#clients-logo").owlCarousel({
    itemsCustom: false,
    pagination: false,
    items: 5,
    autoplay: true,
  })
}); //this part works perfectly
Run Code Online (Sandbox Code Playgroud)
#top-bar {
  background: transparent;
  color: #fff;
  -webkit-transition: all 0.2s ease-out 0s;
  transition: all 0.2s ease-out 0s;
  padding: 30px 0;
  height: 15%;
}
#top-bar .animated-header {
  /*Background Color of nav bar when scrolled*/
  background-color: #ef7c7c;
  padding: 10px 0;
  height: 10%;
  -webkit-box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
}
Run Code Online (Sandbox Code Playgroud)
<header id="top-bar" class="navbar-fixed-top animated-header">
  <div class="container">
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

nnn*_*nnn 9

问题不在于JS使用.addClass(),问题是你的CSS中的选择器是错误的.这个:

#top-bar .animated-header {
Run Code Online (Sandbox Code Playgroud)

应该是这样的:

#top-bar.animated-header {
Run Code Online (Sandbox Code Playgroud)

即,之前取出空间.,因为与具有类的空间中的选择器被匹配元素animated-header是后代的#top-bar.没有空间,#top-bar如果它也有animated-header类,它与元素本身匹配.