0

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

我尝试遵循此处的这些指示: jQuery : add css class to menu item based on browser scroller position

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

我有以下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>

任何帮助都会很棒!

4

1 回答 1

0

您在脚本末尾缺少“)”,这导致 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 和原型时,jquery 的 $ 全局变量与原型 $ 全局变量发生冲突。解决这个问题的一种方法是使用 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>
于 2013-01-14T03:14:14.667 回答