在两个按钮之间添加和删除类列表

问题描述 投票:0回答:1

我的视频项目中有两个按钮,“暂停”和“播放”,并寻找仅应用于当前活动按钮的特殊颜色效果,但单击当前按钮无法删除该按钮上的颜色效果之前被点击过。

目标是可以互换地应用特殊颜色效果。我在这里错过了哪行代码?

const btns = document.querySelectorAll(".switch-btn");

btns.forEach((btn) => {
      btn.addEventListener("click", function(event) {
        const currentBtn = event.currentTarget;

        if (!currentBtn.classList.contains("active")) {
          currentBtn.classList.add("active")
        } else {
          currentBtn.classList.remove("active")
        }

      })
<div class="btns">
  <button class="switch-btn" data-control="pause">Pause</button>
  <button class="switch-btn" data-control="play"> Play</button>
</div>

javascript
1个回答
0
投票

首先,从所有按钮中删除“active”类,然后仅将“active”类添加到单击的按钮:

<div class="btns">
    <button class="switch-btn" data-control="pause">Pause</button>
    <button class="switch-btn" data-control="play">Play</button>
</div>

<script>
const btns = document.querySelectorAll(".switch-btn");

btns.forEach((btn) => {
    btn.addEventListener("click", function(event) {
        btns.forEach(button => {
            button.classList.remove("active");
        });
        
        event.currentTarget.classList.add("active");
    });
});
</script>

<style>
.switch-btn {
    padding: 10px 20px;
    margin: 5px;
    cursor: pointer;
}

.switch-btn.active {
    background-color: #f5c453;
    color: white;
}
</style>
© www.soinside.com 2019 - 2024. All rights reserved.