【发布时间】:2014-07-24 15:35:13
【问题描述】:
以下 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");
});
确实有效。
但是当我将它添加到我的主页时,我必须刷新页面才能添加“固定”类。但我希望在向下滚动时实时添加课程,而无需刷新页面。这在 jsfiddle 中有效,为什么它在我的页面上无效?
我的页面:Click here
【问题讨论】:
-
尝试添加
$(function(){ /* your js code here */ });。 -
@Aleksandar 没有尝试过,但它不会改变任何东西。
$(window)在 DOM 准备好之前定义。 -
检查页面上的控制台会出现错误:索引第 34 行上的“未定义不是函数”,即以下行:
if($(window).scrollTop() > 50) $("header").addClass("fixed"); -
您的
$符号已被覆盖。使用jQuery而不是$ -
@SimonMathewson 试试 Karl-Andre 所说的,或者将其包装在一个自执行函数中,将 jQuery 作为参数传递。
(function($) { /* Code here */ }(jQuery))
标签: javascript jquery html css scroll