You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过纯CSS实现内容的显示/隐藏切换

纯CSS实现内容切换方案

直接通过单选框的:checked状态结合CSS通用兄弟选择器就能实现你的需求,无需JavaScript。以下是修改后的完整代码:

完整CSS代码

.toggle-on-content{
  color: #dd7e6b
}

.toggle-off-content{
  color: #6bbedd
}

/* 默认状态:显示A对应内容,隐藏B对应内容 */
.toggle-off-content {
  display: none;
}

.btn {
    border: 3px solid #16982b;
    display: inline-block;
    padding: 3px;
    position: relative;
    text-align: center;
    transition: background 600ms ease, color 600ms ease;
}

input[type="radio"].toggle {
    display: none;

    & + label {
        cursor: pointer;
        min-width: 60px;

        &:hover {
            background: none;
            color: #16982b;
        }

        &:after {
            background: #16982b;
            content: "";
            height: 100%;
            position: absolute;
            top: 0;
            transition: left 200ms cubic-bezier(0.77, 0, 0.175, 1);
            width: 100%;
            z-index: -1;
        }
    }

    &.toggle-left + label {
        border-right: 0;

        &:after {
            left: 100%;
        }
    }

    &.toggle-right + label {
        margin-left: -5px;

        &:after {
            left: -100%;
        }
    }

    &:checked + label {
        cursor: default;
        color: #fff;
        transition: color 200ms;

        &:after {
            left: 0;
        }
    }
}

/* 切换逻辑:选中B时,显示B内容,隐藏A内容 */
#toggle-off:checked ~ .toggle-off-content {
  display: block;
}
#toggle-off:checked ~ .toggle-on-content {
  display: none;
}

对应的HTML代码(无需修改)

<input id="toggle-on" class="toggle toggle-left" name="toggle" value="false" type="radio" checked>
<label for="toggle-on" class="btn">A</label>
<input id="toggle-off" class="toggle toggle-right" name="toggle" value="true" type="radio">
<label for="toggle-off" class="btn">B</label>
<p class="toggle-on-content">
A lifecycle method is any method that is annotated with @BeforeAll, @AfterAll, @BeforeEach or @AfterEach annotation. The lifecycle methods execute before or after executing the actual test methods.
</p>

<p class="toggle-off-content">
To see how this works, let’s take a look at the following example:
</p>

核心逻辑说明

  • 默认状态:通过.toggle-off-content { display: none; }隐藏B对应的内容,同时保留A内容的默认显示
  • 选中按钮B时,利用#toggle-off:checked ~ .toggle-off-content选择器显示B内容,再通过#toggle-off:checked ~ .toggle-on-content隐藏A内容
  • 选中按钮A时,由于单选框互斥,#toggle-on会自动恢复选中状态,此时B内容回到隐藏状态,A内容正常显示

界面效果示意图

内容的提问来源于stack exchange,提问作者flyingfox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:32:49