css骚操作 — tab切换

效果图

原理

我们知道,tab切换的特点就是当前只有一个显示的内容,其余都是不可见的,也就是说当前只有一个"选中"的对象,因此我们可以借助inputradio类型进行"捕获"用户到底点了哪个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

这里用的是scss预处理器:

$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
  }
}

作者:聪明的汤姆
来源:掘金

THE END