tab选项卡
原生JavaScript很容易做一个Tab选项卡
这里主要的是用HTML5新增的标签选择器querySelector和类名操作方法(dataset、classList等)
效果如下:
body部分
//需求:当用户点击某个模块的时候,给该模块添加样式,对应的内容显示出来
//获取所有的a标签
var navs = document.querySelectorAll("nav a");
//先显示一部分内容(H5标签选择器默认选每一类标签的第一个)
document.querySelector("section").style.display="block";
//遍历该数组
for(var i=0; i
navs[i].onclick = function(){
//每次点击前都先清除原来的内容
var beforeNav = document.querySelector(".active")
var beforeId = beforeNav.dataset["cont"];
document.querySelector("#"+beforeId).style.display="none";
//排他思想
for(var j=0; j
//先去除所有的active标签
navs[j].classList.remove("active");
}
//对应的a加样式
this.classList.add("active");
//获取对应的内容标签并添加样式
var secId = this.dataset["cont"];
document.querySelector("#"+secId).style.display = "block";
}
}
head部分
.tabs {
width: 400`px;
margin: 30px auto;
border: 1px solid #eee;
box-sizing: border-box;
}
.tabs nav {
height: 40px;
text-align: center;
line-height: 40px;
overflow: hidden;
background-color: #06f;
display: flex;
}
nav a{
display: block;
width: 100px;
border-right: 1px solid #eee;
color: #fff;
text-decoration: none;
}
nav a:hover {
color:#fff;
text-decoration: none;
}
nav a:last-child {
border-right: 0 none;
}
nav a.active {
background: #0f6;
color: #fff;
text-decoration: none;
}
.cont {
overflow: hidden;
display: none;
}
.cont ol {
line-height: 30px;
}