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

咨询CSS点击checkbox触发toggle按钮背景渐变平滑过渡的实现方法

CSS 本身不支持直接对渐变背景做过渡,我们可以通过调整渐变背景的位置来实现平滑切换效果,具体实现如下:

修改思路

  1. 把渐变背景的尺寸设置为200%宽度,默认展示其中一半区域
  2. 给背景添加background-position过渡属性,选中状态下切换背景的展示位置,即可实现平滑滑动的过渡效果
  3. 修正原代码中.toggle-button类选择器遗漏.前缀的错误,保证样式正常生效

完整代码

CSS代码

.toggle-button {
  position: relative;
  display: inline-block;
  width: 120px;
  height: 40px;
  margin-left: 100px;
}

.toggle-button input{
  opacity: 0;
  height: 0;
  width: 0;
}

.options-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, gray 50%, white 50%) right;
  background-size: 200% 100%;
  border-radius:3px;
  transition: background-position .4s ease;
}

.button-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  justify-items: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background: linear-gradient(to right, white 50%, black 50%) right;
  background-size: 200% 100%;
  -webkit-background-clip: text;
  transition: background-position .4s ease;
  cursor: pointer;
}

.toggle-button input:checked + .options-wrapper {
  background-position: left;
}

.toggle-button input:checked + .options-wrapper > .button-options {
  background-position: left;
}

.button-options > p {
  color: transparent
}

HTML代码

<label class="toggle-button">
    <input type="checkbox">
    <div class="options-wrapper">
        <div class="button-options">
            <p>Daily</p>
            <p>Hourly</p>
       </div>
    </div>
</label>

效果展示

  • 未选中状态
    状态一:checkbox未触发
  • 选中状态
    状态二:checkbox已触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:27:03