主要方法:
1.所有元素全部清除样式(干掉其他人)
2.给当前元素设置样式(留下我自己)
代码:
<!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 type="text/css">
button{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
<script>
var btns=document.getElementsByTagName('button');
for(var i=0;i<btns.length;i++){
btns[i].onclick=function(){
for(var j=0;j<btns.length;j++){
btns[j].style.backgroundColor=''
}
this.style.backgroundColor='black';
}
}
</script>
</body>
</html>
效果:
注意事项:
1.的‘’中间无空格。
2.this不可以替换为btns[i],function和循环一起用都不可使用类似btns[i]类似方法。因为i值并不会锁定,点击的时候i值为5,下面将进行试验
代码:
<!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 type="text/css">
button{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
</body>
<script>
var btns=document.querySelectorAll("button");
for(var i=0;i<btns.length;i++){
btns[i].onclick=function(){
console.log(i);
for(var j=0;j<btns.length;j++){
btns[j].style.backgroundColor="red";
}
btns[i].style.backgroundColor="black";
}
}
</script>
</html>
效果: