<!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>tab切换案例</title>
<style>
*{
padding: 0;
}
.tab{
margin: 0 auto;
width: 1000px;
}
.tab .tabBtns{
font-size: 14px;
width: 1000px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: #f0f0f0;
}
.tab .tabBtns ul li{
padding: 0 12px;
list-style: none;
float: left;
margin-right: 25px;
}
.active{
color: #fff;
background-color: red;
}
.tabContents p{
display: none;
}
</style>
</head>
<body>
<div class="tab">
<div class="tabBtns">
<ul>
<li class="active">商品介绍</li>
<li>规格与包装</li>
<li>售后保障</li>
<li>商品评价(50000)</li>
<li>手机社区</li>
</ul>
</div>
<div class="tabContents">
<p class="item" style="display: block;">商品模块</p>
<p>主题模块</p>
<p>套餐模块</p>
<p>优惠模块</p>
<p>生产模块</p>
</div>
</div>
<script>
window.onload = function(){
// 获取元素
var tabBtns = document.querySelector('.tabBtns');
var lis = document.querySelectorAll('li');
var pNodes = document.querySelectorAll('p')
// 绑定点击事件
for(var i =0 ; i<lis.length; i++){
// 这一步是需要设置一个自定义属性索引下标
lis[i].setAttribute('index',i);
lis[i].onclick = function(){
for(var i = 0; i<lis.length; i++){
lis[i].className = '';
}
this.className = 'active';
// 在这里获取索引下标
var index = this.getAttribute('index');
for(var i = 0; i<pNodes.length; i++){
pNodes[i].style.display = 'none';
}
pNodes[index].style.display = 'block';
}
}
}
</script>
</body>
</html>