javascript - 是否可以一次只打开我的一个折叠式?
问题描述
我正在使用一排排可折叠的东西。我想让我的网站看起来更专业,所以我的目标是让它一次只能打开一个可折叠的。这是我目前使用的 JavaScript:
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
这是可折叠的html:
<button type="button" class="collapsible"></button>
<div class="content"></div>
有什么办法可以让我一次只能打开一个可折叠的?
解决方案
我会这样做以使其关闭其他打开的行。
这是一个测试:https ://jsfiddle.net/up3t4129/
您需要了解的一件事是确保遍历所有其他打开的,然后关闭它们,这样您就可以获得您想要的结果。
我对代码做了一些评论,以便您更容易理解。
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
// here we are gonna loop through the elements
for(item of coll){
// and remove .active class on the button
item.classList.remove("active");
// here we are checking the next element and making it don't display
item.nextElementSibling.style.display = "none";
}
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
推荐阅读
- javascript - 带有循环javascript的报价生成器
- php - 通过对象在 Laravel 中使用存储门面
- javascript - 如何为所有项目设置相同的高度
- xamarin.forms - UWP 中的 MasterDetailPage“拆分”
- android - 回收站视图未在实时更新时更新
- wpf - 使用 INotifyPropertyChanged 的 WPF Xaml 绑定类实例
- java - SpringMVC 无法返回 Json 或 Xml,Http 406
- laravel-5 - Vue.js - 使用 vue-headful 处理元数据
- jquery - bootstrap-datepicker-rails 选项未应用
- nlp - Python中的塞纳语义角色标签