下面是用JS简单地实现选项卡功能的实例。
注意点:(1)闭包后,要使用立即执行函数;
(2)绑定事件注意参数;
(3)思路:将当前div显示,其余隐藏,给button绑定事件,触碰后显示相应内容。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选项卡练习</title>
<!--CSS样式-->
<style type="text/css">
.wrapper {
box-shadow: -2px 0 5px lightsteelblue, 0 -2px 5px lightsteelblue, 0 2px 5px lightsteelblue, 2px 0 5px lightsteelblue;
height: 450px;
width: 533px;
}
.content {
display: none;
width: 530px;
height: 395px;
margin-top: 8px;
box-shadow: -2px 0 5px gray, 0 -2px 5px gray, 0 2px 5px gray, 2px 0 5px gray;
}
/*点击该按钮的时候显示该颜色*/
.active {
background-color: lightsteelblue;
}
button {
background-color: lightseagreen;
margin-top: 5px;
list-style-type: none;
width: 125px;
height: 40px;
font-family: "新宋体";
font-size: 18px;
border: none;
box-shadow: -2px 0 5px lightsteelblue, 0 -2px 5px lightsteelblue, 0 2px 5px lightsteelblue, 2px 0 5px lightsteelblue;
}
button:first-child {
margin-left: 10px;
}
</style>
</head>
<body>
<!--布局样式-->
<div class="wrapper">
<!--选项卡-->
<button class="active">选项卡一</button>
<button>选项卡二</button>
<button>选项卡三</button>
<button>选项卡三</button>
<div class="content" style="display: block;">
<img src="img/pic-one.png" />
</div>
<div class="content">
<img src="img/pic-two.png" />
</div>
<div class="content">
<img src="img/pic-three.png" />
</div>
<div class="content">
<img src="img/pic-fou.png" />
</div>
</div>
<!--JS代码-->
<script type="text/javascript">
// 将按钮和盒子拿出来
var btn = document.getElementsByTagName('button');
var div = document.getElementsByClassName('content');
// 每一个button上面绑定事件
for(var n = 0; n < btn.length; n++) {
//生成闭包的立即函数
(function(i) {
btn[n].onclick = function() {
for(var m = 0; m < btn.length; m++) {
btn[m].className = ""; //清空效果
div[m].style.display = "none";
}
//当前点击的button设置变化
this.className = "active";
div[i].style.display = "block";
}
}(n))
}
</script>
</body>
</html>
演示效果:
元气少女,加油!