之前上传了一个jquery实现tab栏切换,这个是原生js实现tab栏切换的案例,不多说直接上代码!
同样复制粘贴就能看到效果哦!
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.Box{
width: 240px;
border: 1px solid #000;
margin:100px auto;
padding:20px;
}
.con{
width: 100%;
height: 200px;
background-color: #cccccc;
border: 1px solid #000;
margin-top:10px;
display:none;
}
.current{
background-color: pink;
}
</style>
</head>
<body>
<div class="Box" id="box">
<button class="current" >按钮1</button>
<button >按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<div class="con" style="display:block">内容1</div>
<div class="con">内容2</div>
<div class="con">内容3</div>
<div class="con">内容4</div>
</div>
<script>
// 首先要获得所有的按钮
var box = document.getElementById('box');
var btns = document.getElementsByTagName('button');
var divs = box.getElementsByTagName('div');
for(var i=0;i<btns.length;i++){
var btn = btns[i];
btn.index = i;// 给每个按钮添加一个自定义属性,用来存储当前的索引
btn.onclick = function(){
for(var j=0;j<btns.length;j++){
btns[j].className = '';
}
this.className = 'current';
for(var k = 0;k<divs.length;k++){
divs[k].style.display = 'none';
}
divs[this.index].style.display = 'block';
}
}
</script>
</body>
</html>