这个太狡猾了!我花了好几个小时在这个问题上,却找不到类似的东西,可能是因为我不知道该搜索什么。
问题:
(if 1 or 2 are already open)或如果所有/或没有打开,它应该打开/关闭他们全部。我的代码几乎完成了我需要的所有(if 1 or 2 boxes are open and you click Open-Close All, the remainder opens),如果所有的框都关闭了,Open-Close就会同时打开它们。
唯一不能工作的是,如果所有的框都打开了,我想通过单击Open-Close All.来同时关闭它们。
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 ),但不确定如何编写它。我觉得这可以写得简单得多。
如果你能给我一些指导的话,我会尽我最大的努力使这个例子尽可能的简单。
谢谢!:-)
发布于 2015-10-23 10:04:34
我觉得你的解决办法很简单。基本上,您要做的是检查当用户单击“网站”框外的“主”按钮时显示的项目数量。下面看一看:
//打开/关闭所有框$(‘..Open-关闭所有按钮’).on(单击,函数(){ 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
}
});
});发布于 2015-10-23 09:46:58
可以使用带有类名的.toggleClass()函数作为参数和条件,以检查可见元素的长度:
$('.open-close-all-button').on('click', function(){
event.preventDefault();
$('.small-box').siblings().toggleClass('is-visible',$('.small-box').length != $('.small-box.is-visible').length);
});工作演示
发布于 2015-10-23 10:21:35
全工作解决方案:(复制、粘贴和检查)
在您自己的代码中需要进行非常小的更改,正确的Javascript代码将是这样的。
$(document).ready(function(){
// Toggle individual boxes when clicking on buttons inside container
$('.small-box-button').on('click', function(e){
$(this).next('.small-box').toggleClass('is-visible');
});
// Open/close all boxes
$('.open-close-all-button').on('click', function(e){
if($(".small-box.is-visible").length < $(".small-box").length){
$(".small-box:not([class*='is-visible'])").addClass("is-visible");
}else{
$(".small-box").removeClass("is-visible");
}
});
});另外,我已经更新了您的示例链接,它运行得很好,请查看下面的链接,并测试它是否满足您的需要:)
http://codepen.io/anon/pen/bVLvRK
https://stackoverflow.com/questions/33299265
复制相似问题