说到Tab切换,你可能首先想到的就是使用jQuery,短短几行代码就可以轻松搞定一个Tab切换。而今天所要分享的,是使用 0 行JS代码来实现Tab切换!
方法一:模拟单选框原理
1. HTML结构
<!--HTML-->
<ul>
<li>
<input id="tab1" type="radio" name="tab" checked>
<label for="tab1">选项一</label>
<div class="content">选项一内容</div>
</li>
<li>
<input id="tab2" type="radio" name="tab">
<label for="tab2">选项二</label>
<div class="content">选项二内容</div>
</li>
<li>
<input id="tab3" type="radio" name="tab">
<label for="tab3">选项三</label>
<div class="content">选项三内容</div>
</li>
</ul>
① label需要绑定input,方法就是label的for属性值与input的id一致,这样当点击label元素时input单选框就会被选中
② input、label和div三者是有顺序的,不能随意调换顺序(原因后面你就知道了)
2. CSS样式
/*CSS*/
*{ margin: 0; padding: 0;}
ul{ position: relative; width: 300px; margin: 100px auto;}
ul li{ list-style: none;}
ul li input{ display: none;}
ul li label{ float: left; width: 100px; text-align: center; line-height: 30px; border: 1px solid #000; border-right: 0; box-sizing: border-box; cursor: pointer; transition: all .3s;}
ul li input:checked+label{ color: #fff; background-color: #000;}
ul li:last-child label{ border-right: 1px solid #000;}
ul li .content{ opacity: 0; visibility:hidden; position: absolute; left: 0; top: 31px; width: 100%; height: 300px; border: 1px solid #000; box-sizing: border-box; font-size: 24px; text-align: center; line-height: 300px; color: #fff; transition: all .3s;}
ul li:nth-child(1) .content{ background-color: #0f0;}
ul li:nth-child(2) .content{ background-color: #00f;}
ul li:nth-child(3) .content{ background-color: #f0f;}
ul li input:checked~.content{ opacity: 1; visibility:visible;}
方法二::target伪类
1. HTML结构
<!--HTML-->
<ul>
<li>
<div class="content" id="content1">选项一内容</div>
<a href="#content1">选项一</a>
</li>
<li>
<div class="content" id="content2">选项二内容</div>
<a href="#content2">选项二</a>
</li>
<li>
<div class="content" id="content3">选项三内容</div>
<a href="#content3">选项三</a>
</li>
</ul>
① 每个a标签的href属性须与其兄弟节点.content元素的id值一致
② .content元素与a标签的顺序不能更改
2. CSS样式
/*CSS*/
*{ margin: 0; padding: 0;}
a{ text-decoration: none; color: #000;}
ul{ position: relative; width: 300px; margin: 100px auto;}
ul li{ list-style: none;}
ul li a{ float: left; width: 100px; text-align: center; line-height: 30px; border: 1px solid #000; border-right: 0; box-sizing: border-box; cursor: pointer; transition: all .3s;}
ul li:last-child a{ border-right: 1px solid #000;}
ul li .content{ opacity: 0; position: absolute; left: 0; top: 31px; width: 100%; height: 300px; border: 1px solid #000; box-sizing: border-box; font-size: 24px; text-align: center; line-height: 300px; color: #fff; transition: all .3s;}
ul li:nth-child(1) .content{ background-color: #0f0;}
ul li:nth-child(2) .content{ background-color: #00f;}
ul li:nth-child(3) .content{ background-color: #f0f;}
ul li .content:target{ opacity: 1;}
ul li .content:target+a{ color: #fff; background-color: #000;}
① “.content:target” 将锚链接指向的当前.content元素应用样式
② “.content:target+a” 将锚链接指向的当前.content元素后紧邻的a元素应用样式
总结