【问题标题】:Adding a class on scroll在滚动上添加一个类
【发布时间】:2013-01-14 03:00:53
【问题描述】:

我试图在窗口滚动时简单地添加类 active 并在不滚动时将其删除。

我尝试按照以下说明进行操作: jQuery : add css class to menu item based on browser scroller position

但是,我仍然一定做错了什么。滚动时 id myCart 没有发生任何事情。

我有以下html:

<div id="myCart" class="active">
<div class="add-to-cart">
<div class="clearfix qty_ticker">
<label for="qty">Qty:</label>
<span class="marker_qty_left"> </span>
<input id="qty" class="input-text qty" type="text" title="Qty" value="1" maxlength="12" name="qty">
<span class="marker_qty_right"> </span>
</div>
<button class="button btn-cart" onclick="productAddToCartForm.submit(this)" title="Add to Cart" type="button">
<span>
<span>Add to Cart</span>
</span>
</button>
</div>
</div>

还有以下 javascript 或 jquery:

<script type="text/javascript">
$(window).scroll(function() {    
    // find the id with class 'active' and remove it
    $("#myCart").removeClass("active");
    // get the amount the window has scrolled
    var scroll = $(window).scrollTop();
    // add the 'active' class to the correct id based on the scroll amount
    if (scroll <= 500) {
        $("#myCart").addClass("active");
    }
});
</script>

任何帮助都会很棒!

【问题讨论】:

    标签: jquery scroll


    【解决方案1】:

    您在脚本末尾缺少“)”,导致 javascript 无法编译。

    代码应该是

    <script type="text/javascript">
    $(window).scroll(function() {    
        // find the id with class 'active' and remove it
        $("#myCart").removeClass("active");
        // get the amount the window has scrolled
        var scroll = $(window).scrollTop();
        // add the 'active' class to the correct id based on the scroll amount
        if (scroll <= 500) {
            $("#myCart").addClass("active");
        }
    });
    </script>
    

    当你同时使用jquery 和prototype 时,jquery 的$ 全局变量与prototypes 的$ 全局变量冲突。解决这个问题的一种方法是使用 jquery 的 jQuery 变量

      <script type="text/javascript">
    var $$ = jQuery;
    $$(window).scroll(function() {    
        // find the id with class 'active' and remove it
        $$("#myCart").removeClass("active");
        // get the amount the window has scrolled
        var scroll = $$(window).scrollTop();
        // add the 'active' class to the correct id based on the scroll amount
        if (scroll <= 500) {
            $$("#myCart").addClass("active");
        }
    });
    </script>
    

    【讨论】:

    • 感谢您指出这一点!但是,由于某种原因,它仍然没有做任何事情。我的网站是50.87.6.244/~storeupp/index.php/basketball/… 这个元素是第二个添加到购物车按钮。你能看看为什么它什么都不做。活跃的班级就在那里。
    • 您的页面上似乎缺少 jquery,或者至少我找不到它。尝试添加
    • @tech0925 你确定有一个名为'active'的类吗?
    • 我在代码上方添加了它,它使它工作。但是,在我的标题中,出于某种原因,已经包含 1.6.2 和 1.7.1 版本。此外,当我在代码上方添加您的代码时,它会使其他一半的 jquery 脚本无法正常工作。你有什么建议? @Himal 是的,有一个名为 active 的类。
    • 只使用最新版本的jQuery,在同一页面上没有其他版本的jQuery。
    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多