咨询CSS点击checkbox触发toggle按钮背景渐变平滑过渡的实现方法
CSS 本身不支持直接对渐变背景做过渡,我们可以通过调整渐变背景的位置来实现平滑切换效果,具体实现如下:
修改思路
- 把渐变背景的尺寸设置为200%宽度,默认展示其中一半区域
- 给背景添加
background-position过渡属性,选中状态下切换背景的展示位置,即可实现平滑滑动的过渡效果 - 修正原代码中
.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>
效果展示
- 未选中状态

- 选中状态

内容的提问来源于stack exchange,提问作者ontley
相关产品推荐
相关产品推荐

