<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
width:200px;
height:200px;
background: green;
display: none;
}
.show{
display: block;
}
#blue{
background: blue;
}
#yellow{
background: yellow;
}
</style>
</head>
<body>
<button>绿色</button>
<button>蓝色</button>
<button>黄色</button>
<div class="show"></div>
<div id="blue"></div>
<div id="yellow"></div>
</body>
<script>
var div = document.querySelectorAll('div');
var btn = document.querySelectorAll('button');
//将按钮获取出来,并且将获取出来的按钮赋给一个函数
for(var i = 0;i<btn.length;i++){
btn[i].index = i;
//设置按钮点击事件
btn[i].onclick = function(){
//将原有的的样式清空
for(var a = 0;a<btn.length;a++){
div[a].className = '';
}
//用按钮赋值的函数给样式重新加上样式
div[this.index].className ='show';
}
}
</script>
</html>
网友评论