【问题标题】:Change CSS at a certain scroll level via jQuery doesn't work通过 jQuery 在某个滚动级别更改 CSS 不起作用
【发布时间】:2014-07-24 15:35:13
【问题描述】:

以下 jQuery 代码:

Click here

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() &gt; 50) $("header").addClass("fixed");
  • 您的 $ 符号已被覆盖。使用jQuery 而不是$
  • @SimonMathewson 试试 Karl-Andre 所说的,或者将其包装在一个自执行函数中,将 jQuery 作为参数传递。 (function($) { /* Code here */ }(jQuery))

标签: javascript jquery html css scroll


【解决方案1】:

正如 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))

【讨论】:

    【解决方案2】:

    尝试使用

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

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

    【讨论】:

    • 看看OP的cmets。
    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多