使用JS(ES6)切换手风琴/标签的问题

伊姆兰

我在以下手风琴/标签的布局上有一个小问题:

https://jsfiddle.net/drj3m5tg/

如您所见,在移动设备上,打开和关闭其他标签时,右侧的“ +”图标保持为“-”图标。在桌面视图上,有时需要单击两次选项卡以显示以下内容。我在chrome inspector中检查了一下,可以看到直到再次单击活动类才被删除。有什么办法可以使用JS来解决此问题?

const accordion = document.getElementsByClassName("accordion");
const panel = document.getElementsByClassName("panel");

for(let i = 0; i < accordion.length; i++){
  accordion[i].addEventListener('click', function(){
    removeOpen();
    // add active class to clicked element and open class to next slibling
    const toggleResult = this.classList.toggle('active');
    this.nextElementSibling.classList.toggle('panel-open', toggleResult);


  });
};

 // remove open class for all elements
function removeOpen (){
    for(let i = 0; i < panel.length; i++) {
       panel[i].classList.remove('panel-open');
    }
};
易卜拉欣·马尔里尔

这是因为您必须active从其他accordion按钮中删除该类当您这样做时,您将陷入另一个问题,即切换不再起作用。因此,我建议您这样处理(重构整个过程):

(function() {                                                           // not really necessary (just to hide our variables from the outside scope)
    const accordion = document.getElementsByClassName("accordion");     // the .accordion buttons (no need for panels, we can get them using nextElementSibling)
    let current = -1;                                                   // the index of the current active accordion element (-1 indicate that currently no element is active)

    for (let i = 0; i < accordion.length; i++) {
        accordion[i].addEventListener('click', function() {             // when clicking a .accordion element
            if (i !== current && current !== -1) {                      // if this is not the currently active element (i !== current), and if there is a currently active element (current !== -1)
                accordion[current].classList.remove('active');          // then desactivate the currently active element
                accordion[current].nextElementSibling.classList.remove('panel-open'); // ...
            }
            this.nextElementSibling.classList.toggle('panel-open');     // now toggle the current element
            current = this.classList.toggle('active') ? i : -1;         // ... (if this element is toggled on, then set current to be this element, if it is toggled off then set current to -1 as there will be no active elements)
        });
    };
})();

JSFiddle

编辑:

current拥有一个值,该值是accordion具有类的当前元素的索引active这样0 <= current < accordion.length可能没有活动元素(所有accordion元素都已关闭),因此我们需要一个值来表明这一点。该值不能在上述范围内。它可以是任何东西:nullfalse"oompa loompa",...既然是普遍在使用-1(如indexOf做指示inexistance),我选择了它。

至于为什么要使用它呢?好吧,我们不必跟踪每次单击一个元素就从所有元素中删除活动类的情况,而只是跟踪活动元素,而每次单击另一个元素时,我们只会从一个元素(其索引存储在中current中将它们删除由于current还表明没有元素,因此我们必须先进行测试(current !== -1)。

单击元素时,我们还想检查它是否不是活动元素(i !== -1)。因为如果不这样做,那么我们将删除内部的活动类iftoggles将把它们重新添加回去。因此,如果没有此测试,则单击活动元素时,它将保持活动状态。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章