首页 > 解决方案 > 如何在 CSS 中创建一个活动选项卡?

问题描述

我正在使用在以下位置找到的垂直选项卡:https ://codeconvey.com/pure-css-responsive-vertical-tabs/但我需要一些 CSS 帮助。有没有办法让活动标签背景变成不同的颜色?我只尝试了一个示例,但没有成功:

    input[name="tab"]:checked + label{
       background-color: green !important
    }

标签: css

解决方案


它似乎不支持该功能。我对此的解决方案是创建一个自定义类,在活动选项卡上进行所需的更改,并使用一个简单的 jQuery 脚本来处理该onclick事件。

我将提供一个示例来说明我的意思:

var label = $( '.tabs-container label' );

label.on( 'click', function() {
  label.removeClass( 'active' );
  $( this ).addClass( 'active' );
} )
.tabs-container{
   position: relative;
   background: #2652CC;
   width: 120px;
   height: 100vh;
   float: left;
   z-index: 20;
}

.tabs-container label{
   position: relative;
   padding: 10px;
   border-bottom: 1px solid rgba(0, 0, 0, 0.1);
   display: block;
   font-size: 13px;
   color: #fff;
   cursor: pointer;
   user-select: none;
}

.tabs-container label:hover{
  background: rgba(0, 0, 0, 0.2);
}

.tab-content{
   position: relative;
   background: #eee;
   width: calc(100% - 120px);
   min-height: 100vh;
   padding: 15px;
   float: left;
   box-sizing: border-box;
   z-index: 19;
   display: none;
}

.tab-content:after{
   content: "";
   clear: both;
}

input[name="tab"]{
   display: none;
}

input[name="tab"]:checked + .tab-content{
   display: block;
   animation: slide 0.5s forwards;
}

@keyframes slide{
   from{
     left: -100%;
     opacity: 0;
   }
   to{
     left: 0;
     opacity: 1;
   }
}

.active {
  background: rgba(0, 0, 0, 0.2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="tabs-container">
   <label for="tab1"> First Tab </label>
   <label for="tab2"> Second Tab </label>
   <label for="tab3"> Third Tab </label>
   <label for="tab4"> Fourth Tab </label>
</section>
    
<input name="tab" id="tab1" type="radio" checked />
<section class="tab-content">
  <h2> Tab Heading </h2>
  <p>Your peragraph goes here.</p>
  <!-- Any other content -->
</section>

<input name="tab" id="tab2" type="radio" checked />
<section class="tab-content">
  <p> Contents for tab 2 </p>
</section>

<input name="tab" id="tab3" type="radio" checked />
<section class="tab-content">
  <p> Contents for tab 3 </p>
</section>

<input name="tab" id="tab4" type="radio" checked />
<section class="tab-content">
  <p> Contents for tab 4</p>
</section>


推荐阅读