2012-09-26 27 views
3

代碼:http://codepen.io/anon/pen/sumIx我如何使用slidetoggle並且一次只允許打開一個div?

$('.module article').hide(); 
}); 
$('.module-content, .module-photo').click(function() { 
    for (var i = 0; i < 5; i++) { 
    $('.module article').slideUp(); 
    } $(this).parent().children('article').slideToggle('slow'); 
}); 

如果你點擊任何的箱子,關閉如預期以前的活動專區

當您嘗試關閉同一個活動的div時,它會右後打開。我如何讓其他所有內容保持一致,但要糾正行爲,以免重新打開?

回答

7

試試這個:

$('.module-content').click(function() { 
    var $this = $(this).closest('section').find('article'); 
    $('.module article').not($this).slideUp(); 
    $this.slideToggle('slow'); 
}); 

http://codepen.io/anon/pen/DBirp

+0

+1的'.closest()'和'.find()',如果OP在文章和section/div之間添加更多標記,它們確實更具彈性。我的回答更多地保留了OP的原始代碼。 '=]' –

+0

@FabrícioMatté你的回答是_fine_,在這種情況下,他可以發表另外一個問題:),_I''joking_,+1使用'not'和註釋良好的代碼。 – undefined

+0

真棒,這實際上完美的作品!謝謝。 – micah

4

jQuery自然地迭代元素集合,所以在這種情況下你的循環是無關緊要的。以下是評論更新的代碼:

$('.module-content').click(function() { 
    //stores a reference to the clicked section's article 
    var article = $(this).parent().children('article'); 
    //hides all other articles 
    $('.module article').not(article).slideUp(); 
    //toggles the clicked one 
    article.slideToggle('slow'); 
}); 

http://codepen.io/anon/pen/dgJDr

相關問題