效果圖
原理
我們知道,tab切換的特點就是當前只有一個顯示的內容,其餘都是不可見的,也就是說當前只有一個“選中”的對象,因此我們可以藉助input的radio類型進行“捕獲”用戶到底點了哪個tab;
html
結構很簡單,隱藏的input、標籤列表、內容列表;
<section class="container">
<!-- 隱藏的radio(默認選中第一項,id是給label用的) -->
<input class="nav1" id="nav1" type="radio" name="nav" checked>
<input class="nav2" id="nav2" type="radio" name="nav">
<!-- 標籤列表 -->
<ul class="navs">
<li>
<label for="li1">標籤1</label>
</li>
<li>
<label for="li2">標籤2</label>
</li>
</ul>
<!-- 內容列表 -->
<ul class="contents">
<li>我是內容1</li>
<li>我是內容2</li>
</ul>
</section>
css
$main: #807af1;
input {
display: none;
}
// 標籤列表
.navs {
display: flex;
list-style: none;
li {
padding: 10px;
}
}
// 內容列表(默認隱藏,選中的才顯示)
.contents {
li {
display: none;
padding: 10px;
}
}
// 標籤選中的樣式(大家可以配合類名使用for循環,這裏寫死兩個標籤)
.nav1:checked~.navs li:first-child,
.nav2:checked~.navs li:last-child {
color: $main;
border-bottom: 1px solid $main;
}
// 內容顯示樣式
.nav1:checked~.contents li:first-child,
.nav2:checked~.contents li:last-child {
display: block;
}
過渡動畫
代碼附加在指定位置即可
// 內容列表
.contents {
li {
animation: fade .5s cubic-bezier(0.075, 0.82, 0.165, 1); // 內容切換動畫(可選)
}
}
// 內容切換動畫(可選)
@keyframes fade {
from {
transform: translateX(20px);
opacity: 0
}
to {
transform: translateX(0);
opacity: 1
}
}
往期系列
這個系列會放許多你不知道的css騷操作,敬請期待!😆
🙌💥歡迎所有前端愛好者關注我的個人微信公衆號,我會不定期分享最新、實用性高的前端文章以及技巧!