Javascript从X元素添加/删除类,但是1

时间:2017-03-03 19:38:18

标签: javascript

所以我有这些flex面板,当我点击其中一个时我添加了两个类,但当我点击另一个时,我想从其他flexes中删除这些类,并仅应用于当前的flex being clicked。上面的代码是我到目前为止所提出的。它有效,但还有其他“干净/优雅”的方式吗?

<div class="panels">
    <div class="panel panel1">
      <p>Hey</p>
      <p>Let's</p>
      <p>Dance</p>
    </div>
    <div class="panel panel2">
      <p>Give</p>
      <p>Take</p>
      <p>Receive</p>
    </div>
    <div class="panel panel3">
      <p>Experience</p>
      <p>It</p>
      <p>Today</p>
    </div>
    <div class="panel panel4">
      <p>Give</p>
      <p>All</p>
      <p>You can</p>
    </div>
    <div class="panel panel5">
      <p>Life</p>
      <p>In</p>
      <p>Motion</p>
    </div>
  </div>

Js片段:

const panels = document.querySelectorAll('.panel');

function toggleOpen(){
    panels.forEach(panel => panel.classList.remove('open','open-active'));
    this.classList.toggle('open');
    this.classList.toggle('open-active');
}
panels.forEach(panel => panel.addEventListener('click', toggleOpen)); 

2 个答案:

答案 0 :(得分:3)

您可以在父元素上收听冒泡的click事件。使用closest方法(FF&amp; Chrome),代码可以简化为:

const panels = document.querySelector('.panels');

panels.addEventListener('click', function(e) {
    const panel = panels.querySelector('.open');
    if (panel) panel.classList.remove('open', 'open-active');
    e.target.closest('.panel').classList.add('open', 'open-active');
}); 

或者,使用闭包记住当前选定的面板:

(function (panels, panel) {
    panels.addEventListener('click', function(e) {
        if (panel) panel.classList.remove('open', 'open-active');
        (panel = e.target.closest('.panel')).classList.add('open', 'open-active');
    });
})(document.querySelector('.panels'));

答案 1 :(得分:-1)

尽管您没有提供HTML,但我相信我了解您正在尝试做的事情。我将用jQuery给它一个镜头。

使用jQuery:

let $all = $('.open', '.open-active');
$(".panel").click(function(event) {
    $all.each(function(index, e2) {
        if (!$(event.target).is(e2)) {
            $(e2).removeClass('open', 'open-active');
        }
    });
});