所以我有这些伸缩面板,当我单击其中的一个时,我在其中添加了两个类,但是当我单击另一个伸缩面板时,我想从其他伸缩中删除这些类,并且仅应用于当前单击的伸缩蜂。到目前为止,上面的代码是我提出的。它有效,但是还有其他“干净/优雅”的方式吗?
<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));
最佳答案
您可以在父元素上监听冒泡的click
事件。使用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');
});
或者,使用一个可以记住当前选定面板的闭包:
(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'));
关于javascript - Javascript从X元素中添加/删除类,但1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42587093/