jquery Javascript折叠面板-折叠所有打开的示例(活动示例除外)

btxsgosb  于 2022-11-22  发布在  jQuery
关注(0)|答案(3)|浏览(169)

我正在使用一个简单的javascript accordion来打开/关闭列表项,如下所示。有没有可能确保所有打开的列表项在打开一个新的列表项时关闭(而不是当前的方法,让每个列表项都保持打开状态,直到它被手动关闭)?
此处为代码:
https://codepen.io/anon/pen/zejJpJ
JS系统

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function () {
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    });
}

HTML语言

<ul class="track-listing">
  <li>
    <button class="accordion">TITLE</button>
    <div class="panel">
    <p>Panel content</p>
    </div>
  </li>
  <li>
    <button class="accordion">TITLE</button>
    <div class="panel">
    <p>Panel content</p>
    </div>
  </li>
  <li>
    <button class="accordion">TITLE</button>
    <div class="panel">
    <p>Panel content</p>
    </div>
  </li>
</ul>
pgccezyw

pgccezyw1#

是的,您可以在打开新 accordion 之前关闭所有其他 accordion :

for (var j = 0; j < acc.length; j++) {
  var button = acc[j];

  if (button === this) continue;

  button.classList.remove("active");
  var panel = button.nextElementSibling;
  panel.style.maxHeight = null;
}

第一个

egmofgnx

egmofgnx2#

是的,您可以再次迭代acc数组,并关闭索引与闭包不同的折叠式。

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function () {
        toggleAccordion(this);
        if (this.classList.contains("active")) {
          for (var j = 0; j < acc.length; j++) {
            if (i != j) {
              acc[j].nextElementSibling.style.maxHeight = null;
            }
          }
        }
    });
}

function toggleAccordion(button) {
  button.classList.toggle("active");
  var panel = button.nextElementSibling;
  if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
  } else {
    panel.style.maxHeight = panel.scrollHeight + "px";
  }
}
niwlg2el

niwlg2el3#

你可以通过一个toggle函数来实现,这个函数可以被一个特定的关闭状态覆盖。这样,你就可以在切换之前关闭除了被点击的那个之外的所有东西。下面是forked pen,代码如下。

var acc = document.getElementsByClassName("accordion")

const toggleAccordian = (acc, open = !acc.classList.contains('active')) => {  
  acc.classList.toggle('active', open)
  const panel = acc.nextElementSibling
  panel.style.maxHeight = open ? panel.scrollHeight + "px" : null  
}

const elems = Array.from(acc)
elems.forEach(a => {
  a.addEventListener('click', () => {
    elems
      .filter(e => e !== a)
      .forEach(e => toggleAccordian(e, false))
    toggleAccordian(a)
  })
})

相关问题