可折叠手风琴展开并立即折叠

Collapsible accordion spreads and collapse instantly

我在表单中放置了一个可折叠的手风琴。按下展开按钮,手风琴展开并瞬间倒塌。如果我不把它放在表格中,它对我来说很好用。这是简化的代码: index.html:

<html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="estilos.css">
    </head>
    <body>
    
    <form  method="post" id="platos">
    
    <button class="accordion">Section 1</button>
    <div class="panel">
    <p>Lorem ipsum...</p>
    </div>

    <button class="accordion">Section 2</button>
    <div class="panel">
    <p>Lorem ipsum...</p>
    </div>

    <button class="accordion">Section 3</button>
    <div class="panel">
    <p>Lorem ipsum...</p>
    </div> 
    
    </form>
    
    <script src="collapsible.js"></script>
    
    </body>
</html>

collapsible.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.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}

您的 form 从按钮中获得了一个动作 submit

你需要像这样添加到你的函数 e.preventDefault()

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

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function (e) {
        e.preventDefault()
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}

对于表单标签内的每个按钮,指定 type="button",这些按钮将停止作为提交:

<button type="button" class="accordion">Section</button>