以下是jQuery代码:
点击这里
HTML:
<header class="header">
<div class="navbar">
Hello
</div>
</header>
CSS:
.header {
background-color: black;
height: 1000px;
width: 300px;
color: white;
text-align: center;
padding: 30px;
}
.fixed .navbar{
border: 10px solid red;
position: fixed;
background-color: white;
}
.navbar {
background-color: blue;
height: 50px;
width: 300px;
color: white;
}
JS:
$(window).scroll( function(){
if($(window).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});
这段代码是有效的。
但是当我将它添加到我的主页时,必须刷新页面才能添加“fixed”类。但我希望在向下滚动时实时添加类,而无需刷新页面。这在jsfiddle中有效,为什么在我的页面上不起作用?
我的页面:点击这里
if($(window).scrollTop() > 50) $("header").addClass("fixed");
- MisterBla$
符号被覆盖了,使用jQuery
替代$
。 - Karl-André Gagnon(function($) { /* 在这里编写代码 */ }(jQuery))
- MisterBla