简体   繁体   English

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

[英]Javascript add/remove classes from X elements but 1

so I have these flex panels where I add two classes when I click in one of them, but when I click in another I want to remove the classes from the other flexes and apply only on the current flex beeing clicked. 所以我有这些伸缩面板,当我单击其中的一个时,我在其中添加了两个类,但是当我单击另一个伸缩面板时,我想从其他伸缩中删除这些类,并且仅应用于当前单击的伸缩蜂。 The code above is what I came up so far. 到目前为止,上面的代码是我提出的。 It works, but is there any other "clean/elegant" way of doing it ? 它可以工作,但是还有其他“干净/优雅”的方式吗?

<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 snippet: 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)); 

You could listen to bubbled click events on the parent element. 您可以在父元素上监听冒泡的click事件。 With the use of the closest method (FF & Chrome), code can be simplified to this: 使用closest方法(FF和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');
}); 

Or, with a closure that remembers the currently selected panel: 或者,使用一个可以记住当前选定面板的闭包:

(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'));

Despite you not having provided your HTML, I believe I understand what you're trying to do. 尽管您没有提供HTML,但我相信我了解您正在尝试做的事情。 I'll give it a shot with jQuery. 我将用jQuery试一试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM