首页 > 解决方案 > CSS 活动样式不保留

问题描述

我试图保持点击按钮处于活动状态,只要它仍然被点击。我已经尝试了很多东西,但这似乎不起作用。彩色效果持续时间不超过 1 秒,并且与点击无关。这是我的代码:

// Add active class to the current button

var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    if (current.length > 0) {
      current[0].className = current[0].className.replace(" active", "");
    }
    this.className += " active";
  });
}
.active {
  background-color: #545454;
}
<div id="myDIV">
  <table class="secondTable">
    <tr>
      <th><button class="btn" style="margin-left: -6px;">button1</button></th>
      <th></th>
      <th></th>
    </tr>
    <tr>
      <th><button class="btn" style="margin-left: -6px;">button2</button></th>
      <th></th>
      <th></th>
    </tr>
  </table>
</div>

我已经尝试了所有可能的事情,但我无法弄清楚问题是什么。造型应该只涉及颜色变化。注意:我的 CSS 看起来像这样.active { background-color: #545454; } 非常感谢!

标签: javascripthtmlcss

解决方案


推荐阅读