2013-03-12 190 views
7

我試圖學習如何使用jQuery,並且我偶然發現了一個問題。首先,我會告訴你導致問題的部分代碼。jQuery點擊切換動畫

HTML

<div id="nav"> 
<div id="button"><p class="scroll" onclick="location.href='#ed';">Education</p></div> 
<div id="button"><p class="scroll" onclick="location.href='#wxp';">Work Experience</p></div> 
<div id="button"><p class="scroll" onclick="location.href='#oact';">Other Activities</p></div> 
<div id="button"><p class="scroll" onclick="window.open('cv.pdf','mywindow');">View as PDF</p></div> 
<div id="arrow_container"><div class="arrow" id="down"></div></div> 

jQuery的

$(document).ready(function(){ 
$("#arrow_container").toggle(
    function() { 
    $("#nav").animate({marginTop:"0px"}, 200); 
     }, function() { 
    $("#nav").animate({marginTop:"-100px"}, 200); 
    }); 
}); 

我想在div #nav,它最初位於外部分屏幕,被點擊的div #arrow_container時向下移動。然後,當再次點擊#arrow_container時,我想#nav向上移動到原來的位置。

目前,沒有發生這種情況。你能告訴我問題是什麼以及我如何解決它?

編輯:a jsfiddle with the code, including some css

編輯2:這個問題似乎得到解決。還要感謝有人忘記了我的用戶名和回覆已被刪除,但他有一些很棒的提示!謝謝!

+0

你可以嘗試重新在的jsfiddle您的問題,或者提供一些CSS或東西,所以我們可以看到你是如何定位#nav? – idrumgood 2013-03-12 17:04:20

+0

另外,如果你開始學習jQuery,我建議不要使用切換,因爲它不再包含在最新版本的jQuery中。 – dev 2013-03-12 17:08:39

+0

@ A.V nope,1.8從1.9開始折舊,不再包括在內。 http://api.jquery.com/toggle-event/ – dev 2013-03-12 17:13:38

回答

14

試試這個:

$("#arrow_container").click(function(event){ 
    event.preventDefault(); 
    if ($(this).hasClass("isDown")) { 
     $("#nav").stop().animate({marginTop:"-100px"}, 200);        
    } else { 
     $("#nav").stop().animate({marginTop:"0px"}, 200); 
    } 
    $(this).toggleClass("isDown"); 
    return false; 
}); 

http://jsfiddle.net/us6sohyg/5/

+0

你也可以在if語句後使用toggleClass('isDown')刪除添加和刪除類冗餘 – 2015-03-06 19:46:11

+0

@BenSewards謝謝,我更新了我的代碼。還添加了Timotheus Triebl的建議。 – tsuensiu 2015-03-31 17:22:40

4

對我來說,沒有工作到100%,我不得不每天有生之前編輯一個stop()事件。 這樣:

$("#arrow_container").click(function(event){ 
event.preventDefault(); 
if ($(this).hasClass("isDown")) { 
    $("#nav").stop().animate({marginTop:"0px"}, 200);   
    $(this).removeClass("isDown"); 
} else { 
    $("#nav").stop().animate({marginTop:"-100px"}, 200); 
    $(this).addClass("isDown"); 
} 
return false; 
});