通过jQuery在特定滚动位置更改CSS无效。

3
以下是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中有效,为什么在我的页面上不起作用?

我的页面:点击这里


1
在您的页面上检查控制台时,会在index的第34行出现错误:“undefined is not a function”,该行代码如下:if($(window).scrollTop() > 50) $("header").addClass("fixed"); - MisterBla
3
你的 $ 符号被覆盖了,使用 jQuery 替代 $ - Karl-André Gagnon
你必须在你的网站中包含jQuery。 - peterpeterson
@BrunoQuintanaFleitas 我完成了。 - Simon Mathewson
1
@SimonMathewson 尝试一下Karl-Andre所说的,或者将其包装在一个自执行函数中,并将jQuery作为参数传递。 (function($) { /* 在这里编写代码 */ }(jQuery)) - MisterBla
显示剩余13条评论
2个回答

4
正如Karl-André所说,你的$对象被覆盖了。为使你的代码可用,你可以采取以下方法之一:
使用jQuery对象:
jQuery(window).scroll( function(){
    if(jQuery(window).scrollTop() > 200) jQuery("header").addClass("fixed");
    else jQuery("header").removeClass("fixed");    
});

或者将所有内容封装在一个自执行函数中,并将jQuery对象作为参数传递:

(function($)
{
    $(window).scroll( function(){
        if($(window).scrollTop() > 200) $("header").addClass("fixed");
        else $("header").removeClass("fixed");    
    });
}(jQuery))

1
尝试使用
$(function() {
    $(window).on('scroll', function(){
        if($(this).scrollTop() > 200) $("header").addClass("fixed");
        else $("header").removeClass("fixed");    
    });
});

http://jsfiddle.net/c9aXS/2/


看一下原帖的评论。 - MisterBla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接