一次只能打开一个手风琴选项卡 [英] Only open one accordion tab at one time

查看:137
本文介绍了一次只能打开一个手风琴选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我手风琴的效果非常好,它在网站上看起来很不错,并且应该可以正常工作。但是,我正在尝试为它增加更多的JavaScript功能,使它看起来更专业。

I have an accordion that works really well, it looks good on the site and works as it should. However, I'm trying to add some more JavaScript functionality to it, to make it more it look more professional.

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

Currently, the accordion allows you to have multiple panels open at one time i.e. if I open one tab, and then open another tab, both tabs will be open at the same time. And the only way to close these panels, is to re-click on the header.

我想要的是一些JavaScript代码,可以防止多个标签在一个时间,所以如果我点击一个新面板,它应该先关闭现有的开放面板。这是手风琴的HTML代码:

What I would like is some JavaScript code that prevents multiple tabs from being open at one time, so if I click on a new panel, it should close the existing open panel first. Here is my HTML code for the accordion:

<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代码,它目前允许一次打开多个选项卡

Here is my JavaScript code in a separate JavaScript file which currently allows multiple tabs to be open at one time

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

Not sure if you need all the CSS, but heres the CSS for showing the panel

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

希望有人能帮忙!提前致谢!

Hopefully someone can help! Thanks in advance!

推荐答案

为了实现这一点,您需要在每次点击时将手风琴的状态重置为原始状态,然后在点击元素上设置所需的类。要做到这一点,您可以提取功能来将类名设置为各自的功能,并根据需要调用它。试试这个:

To achieve this you need to reset the state of the accordion back to its original state on each click, before you set the required classes on the clicked elements. To do that you can extract functionality to set the class names in to their own function and call it as required. Try this:

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);
    }
}

工作示例

这篇关于一次只能打开一个手风琴选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆