javascript - 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; }
非常感谢!
解决方案
推荐阅读
- ubuntu - 不能通过usb安装ubuntu和windows 10?
- python - Pandas - 连接两个特定列或更多列的元素
- ruby-on-rails - 如何访问具有特定父级的类
- javafx - 我试图弄清楚如何使我在 BorderPane 内的 VBox 与 BorderPane/Stage 一起扩展,但仍保持在一定范围内
- javascript - 在 href 中添加多个 GET 值
- python - 在 VPS 上托管多个 Django 实例
- python - 没有“详细”参数的 sklearn 模型的进度条
- javascript - 为什么我的文本没有出现在 jsPdf Autotable 上方?
- apache - Apache 2.4 启动/停止在使用 Shibboleth SP 3.2.0 配置后抛出“未定义符号:ber_sockbuf_io_udp”错误
- sql - 如何将 sql 列与 sparksql 中的另一列相同?