我知道这已被问了一千次,但我仍然无法搞清楚。我有一个简单的跟随this tutorial并且我正在尝试添加“展开/全部折叠”链接。我找到了一种方法来扩展所有,但无法弄清楚如何崩溃它们。 slideToggle()
解决方案的问题是,如果我打开一个解决方案,然后单击它将关闭/打开所有这些链接的链接,但这个链接是预先激活的。
我设置了jsFiddle here.
以下是代码概述:
HTML:
<h2 class="acc_trigger"><a href="#">Div 1</a></h2>
<div class="acc_container">
<div class="block"> Yay content!</div>
</div>
<h2 class="acc_trigger"><a href="#">Div 2</a></h2>
<div class="acc_container">
<div class="block">More Content, Score!</div>
</div>
<h2 class="acc_trigger"><a href="#">Div 3</a></h2>
<div class="acc_container">
<div class="block">Even More Content</div>
</div>
<a href="#" class="acc_expand-all">Expand/Collapse All </a>
JS:
jQuery(document).ready(function($) {
//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers
//On Click
$('.acc_trigger').click(function(){
$('.acc_trigger').removeClass('active').next().slideUp();
//Remove all "active" state and slide up the immediate next container
$(this).toggleClass('active').next().slideDown();
return false; //Prevent the browser jump to the link anchor
});
$('.acc_expand-all').click(function(){
//expand all on click
$('.acc_trigger').addClass('active').next().slideDown();
return false;
});
});
答案 0 :(得分:2)
您必须检查展开/折叠处理程序以查看有多少是打开的,等等,如下所示(updated fiddle):
$('.acc_expand-all').click(function(){
var all = $('.acc_trigger'),
active = all.filter('.active');
if (all.length && all.length === active.length) {
// All open; close them
all.removeClass('active').next().slideUp();
}
else {
// At least some are closed, open all
all.not('.active').addClass('active').next().slideDown();
}
return false;
});
关于您在评论中提出的问题,您可以通过检查已打开的数量以及点击的数据是否已打开来检查您是否应处于“独占”模式,例如(updated fiddle):
$('.acc_trigger').click(function(){
var $this = $(this),
thisActive = $this.hasClass('active'),
active;
// If this one is active, we always just close it.
if (thisActive) {
$this.removeClass('active').next().slideUp();
}
else {
// Is there just one active?
active = $('.acc_trigger.active');
if (active.length === 1) {
// Yes, close it
active.removeClass('active').next().slideUp();
}
// Open this one
$this.addClass('active').next().slideDown();
}
});