一次仅打开一个折叠选项卡

问题描述 投票:0回答:6

我有一个工作得非常好的手风琴,它在网站上看起来不错并且工作正常。不过,我正在尝试为其添加更多 JavaScript 功能,使其看起来更专业。

目前,手风琴允许您一次打开多个面板,即如果我打开一个选项卡,然后打开另一个选项卡,两个选项卡将同时打开。关闭这些面板的唯一方法是重新单击标题。

我想要的是一些 JavaScript 代码,可以防止同时打开多个选项卡,因此,如果我单击一个新面板,它应该首先关闭现有打开的面板。这是我的手风琴 HTML 代码:

<div class="accordion"><b>Heading 1</b></div>
<div class="panel">
    <p class="text-light">Text 1</p>
</div>
<div class="accordion"><b>Heading 2</b></div>
<div class="panel">
    <p class="text-light">Text 2</p>
</div>

这是我在一个单独的 JavaScript 文件中的 JavaScript 代码,当前允许同时打开多个选项卡

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

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
    }
}

不确定您是否需要所有 CSS,但这是用于显示面板的 CSS

div.panel.show {
    display: block !important;
}

希望有人能帮忙!预先感谢!

javascript html accordion
6个回答
11
投票

要实现此目的,您需要在每次单击时将手风琴的状态重置回其原始状态,然后再在单击的元素上设置所需的类。为此,您可以提取功能以将类名称设置到它们自己的函数中并根据需要调用它。试试这个:

var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');

for (var i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        var setClasses = !this.classList.contains('active');
        setClass(acc, 'active', 'remove');
        setClass(panel, 'show', 'remove');

        if (setClasses) {
            this.classList.toggle("active");
            this.nextElementSibling.classList.toggle("show");
        }
    }
}

function setClass(els, className, fnName) {
    for (var i = 0; i < els.length; i++) {
        els[i].classList[fnName](className);
    }
}

工作示例


7
投票

在打开选定的选项卡之前关闭所有打开的选项卡。这将防止同时打开多个选项卡。

// Get all Accordion and Panel
let accHeading = document.querySelectorAll(".accordion");
let accPanel = document.querySelectorAll(".accordion-panel");

for (let i = 0; i < accHeading.length; i++) {
    // Execute whenever an accordion is clicked 
    accHeading[i].onclick = function() {
        if (this.nextElementSibling.style.maxHeight) {
           hidePanels();     // Hide All open Panels 
        } else {
           showPanel(this);  // Show the panel
        } 
    };
}

// Function to Show a Panel
function showPanel(elem) {
  hidePanels();
  elem.classList.add("active");
  elem.nextElementSibling.style.maxHeight = elem.nextElementSibling.scrollHeight + "px";
}

// Function to Hide all shown Panels
function hidePanels() {
  for (let i = 0; i < accPanel.length; i++) {
      accPanel[i].style.maxHeight = null;
      accHeading[i].classList.remove("active");
  }
}
* {box-sizing: border-box;}

/* Style the Headings that are used to open and close the accordion panel */
.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  margin: 0;
  font-weight: 300;
}

/* Change color of the heading and icon (on hover and click) */
.active, .accordion:hover, .accordion:hover::after {
  background-color: #007eff;
  color: white;
}

/* Add "plus" sign (+) after Accordion */
.accordion::after {
  content: '\002B';
  color: #777;
  font-weight: bold;
  float: right;
}

/* Add "minus" sign (-) after Accordion (when accordion is active) */
.active::after {
  content: "\2212";
  color: white;
}

/* Style the accordion panel */
.accordion-panel {
  padding: 0 18px;
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.2s ease-out;
}
<div style="border: 1px solid lightgray;">
  <h2 class="accordion">Section 1</h2>
  <div class="accordion-panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <h2 class="accordion">Section 2</h2>
  <div class="accordion-panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <h2 class="accordion">Section 3</h2>
  <div class="accordion-panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>

  <h2 class="accordion">Section 4</h2>
  <div class="accordion-panel">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  </div>
</div>


4
投票

选择一项时,只需预先隐藏所有项目即可。

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

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        hideAll();

        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
    }
}

function hideAll() {
    for (i = 0; i < acc.length; i++) {
        acc[i].classList.toggle("active", false);
        acc[i].nextElementSibling.classList.toggle("show", false);
    }
}

3
投票
var acc = document.getElementsByClassName("accordion");
var i;
var last;
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        if(last){
            last.classList.toggle("active",false);
            last.nextElementSibling.classList.toggle("show",false);
        }
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
        last=this;
    }
}

变量last将跟踪最后一个活动的手风琴,因此您不需要再次迭代每个手风琴和面板。


0
投票

此功能不需要其他代码,请确保使用与 bootsrap 推荐的相同的 id 类

正确的手风琴代码https://getbootstrap.com/docs/5.0/components/accordion/

<div class="accordion" id="accordionExample">
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingOne">
      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
        Accordion Item #1
      </button>
    </h2>
    <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
  <div class="accordion-item">
    <h2 class="accordion-header" id="headingThree">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
        Accordion Item #3
      </button>
    </h2>
    <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the third item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>
</div>

-1
投票

你必须用手风琴覆盖面板,这样你就可以轻松做到这一点。

参考这个

html
<div class="accordion"><b>Heading 1</b>
    <div class="panel">
        <p class="text-light">Text 1</p>
    </div>
    </div>
<div class="accordion"><b>Heading 2</b>
    <div class="panel">
        <p class="text-light">Text 2</p>
    </div>
    </div>

jquery:
$('.accordion').click(function() {
$(this).find('.panel').show();
$(this).siblings().find('.panel').hide();

});

工作示例

© www.soinside.com 2019 - 2024. All rights reserved.