点击改变DIV背景颜色:JavaScript实现
Div 1
Div 2
Div 3
.box {
width: 100px;
height: 100px;
background-color: #ccc;
margin: 10px;
display: inline-block;
text-align: center;
line-height: 100px;
cursor: pointer;
}
.active {
background-color: #f00;
}
function changeColor(id) {
var element = document.getElementById(id);
var activeElements = document.getElementsByClassName('active');
for (var i = 0; i < activeElements.length; i++) {
activeElements[i].classList.remove('active');
}
element.classList.add('active');
}
在这个例子中,当单击一个div时,它的背景颜色将改变为红色,而其他div的背景颜色将恢复为灰色。通过将'active'类添加到当前单击的div上,我们可以通过CSS样式将其背景颜色更改为红色。我们还使用JavaScript代码来删除其他div上的'active'类,以确保只有一个div具有红色背景颜色。
原文地址: https://www.cveoy.top/t/topic/jKnX 著作权归作者所有。请勿转载和采集!