CSS3 tab選項卡動態切換

admin發表於2018-05-23

本章節分享一段程式碼例項,它利用css3實現了tab選項卡功能。

在css3之前,實現選項卡都要藉助於JavaScript。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.main {
  width: 450px;
  height: 200px;
  margin: 0 auto;
  position: relative;
}
.main > input {
  opacity: 0;
  width: 150px;
  height: 40px;
  position: absolute;
  z-index: 33;
  top: 0;
  cursor: pointer;
}
.main > span {
  width: 150px;
  height: 40px;
  line-height: 40px;
  position: absolute;
  top: 0;
  text-align: center;
  overflow: hidden;
  background: #f0f0f0;
}
.main > span {
  transition: all .5s;
}
.ys {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}
.main > input:hover + span {
  background: rgba(255,255,255,.1);
}
.main > input:checked + span {
  background: #fff;
}
.main > input:hover + span, .main > input :checked + span {
  color: #3498db;
}
#tab-1, #tab-1 + span {
  left: 0;
}
#tab-2, #tab-2 + span {
  left: 33.33%;
}
#tab-3, #tab-3 + span {
  left: 66.66%;
}
.line {
  background: #3498db;
  width: 33.33%;
  height: 4px;
  top: 36px;
  position: absolute;
}
#tab-1:checked ~ .line {
  left: 0;
}
#tab-2:checked ~ .line {
  left: 33.33%;
}
#tab-3:checked ~ .line {
  left: 66.66%;
}
.ease {
  transition: all .5s;
}
.content {
  width: 450px;
  height: 160px;
  padding: 60px 0;
}
.content section {
  width: 450px;
  display: none;
}
.content section div {
  font-size: 18px;
  color: #cc3300;
}
#tab-1:checked ~ .content #tab-item-1 {
  display: block;
}
 
#tab-2:checked ~ .content #tab-item-2 {
  display: block;
}
#tab-3:checked ~ .content #tab-item-3 {
  display: block;
}
</style>
</head>
<body>
<div class="main">
  <input type="radio" id="tab-1" name="tab" checked>
  <span href="#tab-item-1" class="ys">螞蟻部落一</span>
 
  <input type="radio" id="tab-2" name="tab">
  <span href="#tab-item-2" class="ys">螞蟻部落二</span>
 
  <input type="radio" id="tab-3" name="tab">
  <span href="#tab-item-3" class="ys">螞蟻部落三</span>
  <div class="line ease"></div>
 
  <div class="content">
    <section id="tab-item-1">
      <div>內容一</div>
    </section>
    <section id="tab-item-2">
      <div>內容二</div>
    </section>
    <section id="tab-item-3">
      <div>內容三</div>
    </section>
  </div>
</div>
</body>
</html>

相關文章