纯css实现tab切换
前端开发中,经常会用到tab切换,最常用的做法是使用JS处理显示与隐藏,然而在H5开发中, 完全可以做到利用CSS3的伪类选择器实现这个效果,遗憾的是在IE8及以下,不可用。
先看整体效果:
为方便感兴趣的朋友,直接上代码:
html结构:
<div class="tab-box">
<input type="radio" name="demo" id="tab-switch-input1" checked="">
<input type="radio" name="demo" id="tab-switch-input2">
<input type="radio" name="demo" id="tab-switch-input3">
<div class="tab-box-label">
<label for="tab-switch-input1">
<span>tab1</span>
</label>
<label for="tab-switch-input2">
tab2
</label>
<label for="tab-switch-input3">
tab3
</label>
</div>
<div class="tab-contents">
<div class="tab-content">
content 1 显示
</div>
<div class="tab-content">
content 2 显示
</div>
<div class="tab-content">
content 3 显示
</div>
</div>
</div>
相关样式:
<style>
body{
font-family: 'microsoft yahei'
}
.tab-box {
margin: 20px 0;
font-size: 0;
}
.tab-box input {
display: none;
}
.tab-box label {
display: inline-block;
text-align: center;
width: 100px;
background-color: #0064cd;
color: #fff;
font-size: 18px;
line-height: 2;
}
.tab-content {
font-size: 14px;
width: 352px;
height: 200px;
margin-top: 5px;
border: solid 1px slategray;
display: none;
}
.tab-box input:nth-of-type(1):checked ~ .tab-contents .tab-content:nth-of-type(1),
.tab-box input:nth-of-type(2):checked ~ .tab-contents .tab-content:nth-of-type(2),
.tab-box input:nth-of-type(3):checked ~ .tab-contents .tab-content:nth-of-type(3) {
display: block;
}
.tab-box input:nth-of-type(1):checked ~ .tab-box-label label:nth-of-type(1) ,
.tab-box input:nth-of-type(2):checked ~ .tab-box-label label:nth-of-type(2),
.tab-box input:nth-of-type(3):checked ~ .tab-box-label label:nth-of-type(3) {
background-color: #88c846;
color: #fff;
}
</style>
分析:
此方法主要是借助input的checked属性控制其后面元素的显示与否,通过选中tab的nth-of-type属性,控制具体子模块。这也就注定了input和tab-contents必须同级(也即他们有共同的父元素);通过input的id和label的for属性,建立联系。
相关处理方法可以参考Tab Panel, the right way
更多相关文章
- HTML基础 img标签alt属性 当图片加载失败的时候显示为文本
- 如何使用CSS消除元素的偏移?
- KeyPress或KeyDown事件没有得到html元素的buind
- htmlhref属性最大支持多少个字符???(高分)
- 行内元素与块级元素
- 固定定位,父元素具有转换
- HTML语言中img标签的alt属性和title属性的作用与区别
- 在c#中获取html元素的实际边距
- html中插入activex控件之后 需要在 网页中实现控件的属性及方法,