点击到另个按钮的时候怎么取消掉上个按钮的背景色呢?
点击到另个按钮的时候怎么取消掉上个按钮的背景色呢?
定义个类.blue(background: blue, color:#fff), 点击的时候先根据blue类名,找出有这个类的删掉元素的这个类,然后再给当前点击对象添加blue类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.province {
background: #eee;
color: #000;
padding: 2px;
border-radius: 4px;
display: inline-block;
}
.blue {
background: blue;
color: #fff;
}
</style>
</head>
<body>
<div class="all">
<div class="province">北京</div>
<div class="province">天津</div>
<div class="province">上海</div>
</div>
</body>
<script>
let proList = document.getElementsByClassName('province')
for (let i = 0; i < proList.length; i++) {
proList[i].onclick = function () {
let activeItem = document.getElementsByClassName('blue')
if (activeItem.length > 0) {
activeItem[0].classList.remove('blue')
}
proList[i].classList.add('blue')
}
}
</script>
</html>