JavaScript点击高亮
HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 600px;
margin: 50px auto;
}
button {
width: 100px;
height: 40px;
background-color: skyblue;
}
.active {
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<button class="active">1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
</body>
</html>
JavaScript部分
<script>
//获取所有button querySelectorAll
var bts = document.querySelectorAll('.box>button')
// console.log(bts)
handleClick()
function handleClick() {
for (var i = 0; i < bts.length; i++) {
bts[i].onclick = function () {
// 排他思想
// 点击的时候 先把所有的按钮的class全部清空 然后把当前点击的高亮
for (var k = 0; k < bts.length; k++) {
//让类名为空
// bts[k].className = ''
//删除类名active
bts[k].classList.remove('active')
}
// 当前点击的高亮
this.className='active'
// this.classList.add('active')
}
}
}
</script>