我第一次在这里提问。 我搜索了问题,但找不到类似的问题。
我正在使用 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
#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);
}
<header id="top-bar" class="navbar-fixed-top animated-header">
<div class="container">
非常感谢您的帮助!
最佳答案
问题不在于使用 .addClass()
的 JS,问题在于您的 CSS 中的选择器是错误的。这:
#top-bar .animated-header {
应该是这样的:
#top-bar.animated-header {
也就是说,删除 .
之前的空格,因为 选择器匹配具有类 animated-header
的元素 <#top-bar
的 em>后代。 没有空格,如果它也有 animated-header
类,它匹配 #top-bar
元素本身。
关于javascript - addClass removeClass 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894515/