Only open one accordion tab at one time

后端 未结 5 1120
眼角桃花
眼角桃花 2020-12-09 13:44

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 i

5条回答
  •  -上瘾入骨i
    2020-12-09 14:50

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

    Working example

提交回复
热议问题