[英]Changing the background color of a <tr> on click
我试图在单击元素时更改元素的背景颜色。 基本上,我希望能够在每次单击时来回切换此颜色。
这是我正在使用的代码:
function activateButton1() {
var x = document.getElementById('postButton1');
if (x.className == 'postButton1') {
x.className = 'postButton1on';
} else {
x.className = 'postButton1';
}
}
我正在使用两个具有不同背景颜色的不同 CSS 类,但它不起作用。 任何人都可以提供任何见解吗?
这可以通过toggle
方法完成:
function activateButton1() {
this.classList.toggle("postButton1on");
}
您甚至可以在 html 中触发它以简化事情:
<tr onclick="this.classList.toggle('postButton1on')">...</tr>
然后只要.postButton1on
css 在.postButton1
css 之后声明,那么.postButton1on
背景颜色就会覆盖之前设置的内容。
使用 jQuery,您可以通过
$( "#postButton1" ).on('click', function(){
$( this ).toggleClass( "postButton1on" );
};
可能无法正常工作,因为您可能混合使用id
和class
,因为它们具有相同的名称,至少在您发布的 JS 中是这样。 这是打包在 HTML 文档中的所有内容,经过测试可以正常工作:
<!DOCTYPE html>
<html>
<head>
<style>
.off {
background-color: white;
}
.on {
background-color: red;
}
</style>
<script>
function change() {
var x = document.getElementById('post');
if (x.className.match('on')) {
x.className = 'off';
} else {
x.className = 'on';
}
}
function change2() {
var x = document.getElementById('row');
if (x.className.match('on')) {
x.className = 'off';
} else {
x.className = 'on';
}
}
</script>
</head>
<body>
<button id="post" onclick="change()" class="on">hello</button>
<table>
<tr id="row" onclick="change2()" class="on">
<td>hey</td>
<td>hey</td>
</tr>
</table>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.