2013-01-14 4 views
0

윈도우 스크롤에 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> 

그리고 다음과 같은 자바 스크립트 또는 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> 

것은 어떤 도움이 좋을 것을!

답변

0

자바 스크립트를 컴파일하지 못하게하는 스크립트 끝에 ")"이 없습니다. 둘 다 JQuery와 및 프로토 타입, 프로토 타입과 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의 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> 
+0

지적 해 주셔서 감사합니다! 그러나, 그것은 여전히 ​​어떤 이유로 든 아무것도하지 않습니다. 내 웹 사이트는 http://50.87.6.244/~storeupp/index.php/basketball/full-sample-product.html입니다.이 요소는 두 번째 장바구니에 추가 버튼입니다. 당신은 모양을 가지고 왜 그 일을하지 않는지 볼 수 있습니까? 활성화 된 클래스가 그대로 있습니다. –

+0

귀하의 페이지에 jquery가 없거나 최소한 찾을 수 없습니다. RyanFishman

+0

@ tech0925 클래스를 추가 하시겠습니까? '활성'이라고? – Himal