在滚动上添加一个类

时间:2013-01-14 03:00:54

标签: jquery scroll

我试图在窗口滚动上添加类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>

任何帮助都会很棒!

1 个答案:

答案 0 :(得分: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和prototype时,jquery的$ global变量与prototypes $ global变量冲突。解决这个问题的一种方法是使用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>