[英]Keep specific panel of accordion open
我将基本 JS 用于手风琴/可折叠装置,效果很好,除了现在我想在开始时打开一个组中的一个面板。
然后我尝试为此使用 JQueryUI,因为它确实保持一个面板打开以启动,但它不允许同时打开多个面板。 我通读了文档,但看不到在哪里/是否可以配置。
所以我想知道是否有一种方法可以修改我最初拥有的以下内容,或者,如果我遗漏了 JQueryUI 的某些内容。
<script>
var acc = document.getElementsByClassName(" ols-accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");
var
olsPanel = this.nextElementSibling;
if (olsPanel.style.maxHeight) {
olsPanel.style.maxHeight = null;
} else {
olsPanel.style.maxHeight = olsPanel.scrollHeight + "px";
}
});
}
</script>
.ols-accordion {
background-color: #fff;
color: #1e1e1e;
cursor: pointer;
padding: 18px;
width: 85%;
box-sizing: border-box;
border: 1px solid #eaeaea;
border-bottom: 0;
text-align: left;
font-size: 18px;
line-height: 24px;
transition: 0.4s;
}
.olsPanel {
width: 85%;
box-sizing: border-box;
padding: 0 18px;
margin-bottom: 10px;
background-color: #fff;
border: 1px solid #eaeaea;
border-top: 0;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
我是否需要先将 class 或 ID 添加到我想保持打开状态的面板,然后单独编写一些内容,将maxHeight
分配给等于scrollHeight
的元素? 几乎就像我上面的相反?
这是一个使用event.target
的示例,将事件传递给事件侦听器 function,然后使用实际按下的元素来切换 class 以将 CSS 应用于该元素。
编辑:如果您希望在页面加载时打开其中一个元素,只需将show
class 添加到该元素 HTML 中,它就会在页面加载时打开。
//--> Return a node list of all element with the.acc class selector const acc = document.querySelectorAll('.acc') //--> run the event (e) into a function and get the //--> nextElementSibling and toggle a class using //--> classList.toggle() function showPanel(e) { e.target.nextElementSibling.classList.toggle('show') e.target.classList.toggle('btnBG') } //--> forEach loop that will iterate over each element within the //--> node list, assign the variable el, to each matching node within that //--> node list and then assign an eventListener listening for a click //--> we run the function that toggles the class on our sibling element acc.forEach(el => { el.addEventListener("click", showPanel) })
.flex-item { display: flex; flex-direction: column; justify-content: start; align-items: start; width: 100%; }.acc { flex: 0; line-height: 1.5rem; padding: .5rem; border-bottom: 1px solid #DDD; }.acc:nth-of-type(1) { border-top: 1px solid #DDD; }.panel { display: none; }.show { display: inline-block; }.btnBG { background-color: lightgreen; }
<div class="flex-item"> <div class="acc btnBG">Section 1</div> <div class="panel show"> <p>Lorem ipsum...1</p> </div> <div class="acc">Section 2</div> <div class="panel"> <p>Lorem ipsum...2</p> </div> <div class="acc">Section 3</div> <div class="panel"> <p>Lorem ipsum...3</p> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.