这个很棘手!我已经花了数小时的时间,在Stackoverflow上找不到任何类似的东西,可能是因为我不确定要搜索的内容。
问题:
(if 1 or 2 are already open)
,或者如果所有/或全部未打开,则应将其全部打开/关闭。 我的代码几乎完成了我需要的所有
(if 1 or 2 boxes are open and you click Open-Close All, the remainder opens)
,如果所有框都关闭了,则“打开-关闭”功能会一次打开它们。唯一不起作用的是,如果“所有”框都打开了,我希望能够通过单击“打开-全部关闭”来一次将其全部关闭。
http://codepen.io/StrengthandFreedom/pen/ZbrvOO
$('.small-box-button').on('click', function(){
event.preventDefault();
$(this).next('.small-box').toggleClass('is-visible');
});
// Open / Close all / remainders
$('.open-close-all-button').on('click', function(){
event.preventDefault();
if ($('.small-box').is(':visible')) {
// then open the small boxes that are not open yet (the remainders)
$('.small-box').siblings().addClass('is-visible');
// $(this).next('.small-box').toggleClass('is-visible');
}
//not sure what to do here...
else ($('.small-box').not(':visible'))
$('.small-box').siblings().addClass('is-visible');
});
我认为我需要使用更多其他条件,并检查
(like if isVisible >= 1 || 2 )
的值,但不确定如何编写。我觉得这可以写得简单得多。
非常感谢您提供一些指导,我竭尽所能使示例尽可能易于理解。
谢谢! :-)
最佳答案
我认为您的解决方案非常简单。基本上,您要做的就是检查当用户单击主按钮出站框时要显示的项目数。看下面:
//打开/关闭所有框
$('。open-close-all-button')。on('click',function(){
event.preventDefault();
var numOfItems = $('.is-visible').length;
if(numOfItems > 1){ //Add the case you need
//Remove all the .is-visible
}else{
//Add to all the boxes .is-visible
}
});
另外,我建议您封装代码:
$(document).ready(function(){
// Toggle individual boxes when clicking on buttons inside container
$('.small-box-button').on('click', function(){
event.preventDefault();
$(this).next('.small-box').toggleClass('is-visible');
});
// Open/close all boxes
$('.open-close-all-button').on('click', function(){
event.preventDefault();
var numOfItems = $('.is-visible').length;
if(numOfItems > 1){ //Add the case you need
//Remove all the .is-visible
}else{
//Add to all the boxes .is-visible
}
});
});