实现动态切换效果,且按钮位置可变,不固定,可切换至任意位置
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<style type="text/css">
.mod-tab .tab{
float:left;
padding:5px 20px;
border-top:1px solid #ccc;
border-left:1px solid #ccc;
background-color:#ddd;
}
.header .tab:last-child{
border-right:1px solid #ccc;
}
.content{
border:1px solid #ccc;
width:300px;
height:200px;
}
.header::after{
content:'';
display:block;
clear:both;
}
.mod-tab .header .active{
background-color:#fff;
}
.mod-tab .content .panel{
display:none
}
.mod-tab .content .active{
display:block;
}
/*.button1{
position: fixed;
left:500px;
top: 100px
}*/
.tab{
display: block;
}
</style>
<body>
<div class="mod-tab">
<div class="header">
<button class="tab active button1">1</button>
<button class="tab button2">2</button>
<button class="tab button3">3</button>
<button class="tab button4">4</button>
</div>
<div class="content">
<div class="panel active">
<div>panel1</div>
<div>anel1</div>
<div>nel1</div>
</div>
<div class="panel">panel2</div>
<div class="panel">panel3</div>
<div class="panel">panel4</div>
</div>
</div>
</body>
<script type="text/javascript">
document.querySelectorAll('.tab').forEach(function(node){
node.addEventListener('click',function(){
var index
this.parentElement.querySelectorAll('.tab').forEach(function(e,inx){
//e.style.display='none' 跳转的时候隐藏按钮
e.classList.remove('active')
if(node === e){
index=inx
}
})
this.classList.add('active')
this.parentElement.nextElementSibling.querySelectorAll('.panel').forEach(function(panel){
panel.classList.remove('active')
})
this.parentElement.nextElementSibling.querySelectorAll('.panel')[index].classList.add('active')
})
})
</script>
</html>