说明
tab也切换在前端页面中是非常常见的一种效果。本人通过搜集资料大致实现有有下面三种写法。
-
利用:hover 选择器
- 缺点:只有鼠标在元素上面的时候才有效果,无法实现选中和默认显示某一个的效果
-
利用a标签的锚点 + :target选择器
- 缺点:因为锚点会将选中的元素滚动到页面最上面,每次切换位置都要移动,体验极差。
-
利用label和radio 的绑定关系和radio选中时的:checked 来实现效果
radio控件和label控件绑定
只要指定label的"for"属性到radio的id就行,或者用label标签包围住radio。
第一种方式:
<input type="radio" id="radio-first" name="radio1" /><label for="radio-first">这是radio-first</label>
<input type="radio" id="radio-second" name="radio1" /><label for="radio-second">这是radio-second</label>
第二种方式:
<label><input type="radio" name="radio2">这是radioA</label>
<label><input type="radio" name="radio2">这是radioB</label>
下面利用第三种方式实现tab效果
css样式
<style>
/* 清样式,如果是项目中,不推荐使用通配符来清样式,建议使用标签清样式,通配符清样式会增加页面压力 */
*{
margin:0;
padding:0;
}
/* 宽度为屏宽的一半,高度为屏高的一半,然后居中 */
.box{
width:50vw;
height:50vh;
margin:0 auto;
}
/* 清除li样式 */
ul,li{
list-style: none;
}
/* 将ul相对定位,目的是让内容的div绝对定位时相对ul定位,否则会相对body定位 */
/* ul弹性盒,目的是让li横着排,也可以将li浮动或者转行内块 */
ul{
position:relative;
display:flex;
}
/* 将三个li宽度平分,高度60px */
li{
flex:1;
height:60px;
}
/* input隐藏 */
input{
display:none;
}
/* 设置input的下一个节点label的样式 */
input+label{
display:block;
width:100%;
height:100%;
background:#ccc;
font-size:18px;
text-align: center;
line-height: 60px;
color:#333;
}
/* 设置div内容的基础样式 隐藏内容div*/
input+label+div{
display:none;
position: absolute;
left:0;
top:60px;
}
/* input选中状态时候对应的label的样式 */
input:checked+label{
background: #333333;
color:#fff;
}
/* input选中时候显示对应的div */
input:checked+label+div{
display:block;
}
.tab-box{
width: 50vw;
height: 300px;
background-color: darkred;
}
</style>
HTML代码
<div class="box">
<ul>
<li>
<input type="radio" name="check" id="active1" checked>
<label for="active1">第一页</label>
<div class="tab-box">1道德三皇五帝,功名夏后商周,五霸七雄闹春秋</div>
</li>
<li>
<input type="radio" name="check" id="active2"><label for="active2">第二页</label>
<div class="tab-box">2诸恶莫作,众善奉行,远报儿女,近在己身诸恶莫作</div>
</li>
<li>
<input type="radio" name="check" id="active3"><label for="active3">第三页</label>
<div class="tab-box">3rrererererererere</div>
</li>
</ul>
</div>
执行效果

|