在开发中看见仅使用css技巧,就用HTML的Radio Input来实现的Tab的切换,连click事件都未使用。代码效果如下:
<!DOCTYPE HTML>
<html>
<header>
<link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
<style>
input {
display: none;
}
input:checked + label {
color: #2d3538;
border-top: 2px solid #148ac4;
border-bottom: 1px solid #fff;
background-color: white;
}
label:hover {
cursor: pointer;
background: #148ac4 ;
}
.label-tab {
display: inline-block;
width: 100px;
padding: 0 10px 0 10px;
text-align: center;
background: #eee;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.fa {
padding-right: 5px;
}
.tab-panel {
visibility: hidden;
position: absolute;
width: 300px;
height: 100px;
border: 1px solid #333;
}
#admin-tab:checked ~ #admin-panel,
#user-tab:checked ~ #user-panel {
visibility: visible;
}
</style>
</hearder>
<body>
<input id="admin-tab" type="radio" name="tab" value="admin" checked="true"/>
<label for="admin-tab" class="label-tab"><i class="fa fa-users" aria-hidden="true"></i>管理员</label>
<input id="user-tab" type="radio" name="tab" value="user" />
<label for="user-tab" class="label-tab"><i class="fa fa-user" aria-hidden="true"></i>普通用户</label>
<div id="admin-panel" class="tab-panel">
我是管理员
</div>
<div id="user-panel" class="tab-panel">
我是普通用户
</div>
</body>
</html>
1. label的for属性要和对于的input的id值保持一致,点击label时才能相当于点击了对应的radio button。
2. 使用#admin-tab:checked ~ #admin-panel之类样式来设置对应的panel是否显示。
3. 使用input:checked + label来设置label选中后的样式效果。
4. 使用label:hover来设置鼠标在label上的样式效果。
5. 图标使用了流行的font-awesome,<i class="fa fa-users" aria-hidden="true"></i>即对应相应的图标。
6. label的display需要设置成块级显示,否则width样式不起作用。