今天我们制作一个tab栏切换废话不多说直接上代码
下面是css样式
*{
margin: 0;
padding: 0;
text-decoration: none;
}
.nav a{
width: 180px;
height: 35px;
display: block;
float: left;
color: #fff;
background-color: #999;
text-align: center;
line-height: 35px;
margin-right: 15px;
}
.nav .hover{
background-color: blue;
}
.nav_con>div:nth-child(1){
width: 570px;
height: 300px;
background-color: red;
display: none;
clear: both;
}
.nav_con>div:nth-child(2){
width: 570px;
height: 300px;
background-color: greenyellow;
display: none;
clear: both;
}
.nav_con>div:nth-child(3){
width: 570px;
height: 300px;
background-color: pink;
display: none;
clear: both;
}
.nav_con>div:first-child{
display: block;
}
上面的是一些样子可以凭自己喜好编写样式
下面是html的代码
<div class="tab">
<div class="nav">
<a href="#" class="hover">公司新闻</a>
<a href="#">行业资讯</a>
<a href="#">公司详情</a>
</div>
<div class="c"></div>
<div class="nav_con">
<div class="a">公司新闻内容</div>
<div>行业资讯内容</div>
<div>公司详情内容</div>
</div>
</div>
接下来是js代码简单易懂
<script>
var navs = document.querySelectorAll(".nav a");
var thisindex = 0;
var nav_cons = document.querySelectorAll(".nav_con>div");
//给每一项添加点击事件和加上自定义属性index
for(var i=0;i<navs.length;i++){
//给每一项 加上index索引
navs[i].setAttribute("index",i);
//点击事件
navs[i].onclick = function(){
//当nav 导航点击的时候 给全局thisindex赋值
thisindex = this.getAttribute("index");
for(var j =0;j<navs.length;j++){
navs[j].className=""; //去除所有的hover样式
nav_cons[j].style.display = "none"; //让所有的tab 页内容隐藏
}
this.className="hover";
nav_cons[thisindex].style.display ="block"; //让所有的tab 页内容显示
}
}
</script>
这样就写好了