如何实现Checkbox Toggle Slider取消勾选后平滑滑动回初始位置?
修复Checkbox Toggle Slider取消勾选时的平滑回退问题
你的问题出在使用animation实现滑动效果——动画执行完毕后元素会回到初始位置,且未配置取消勾选时的反向过渡逻辑。改用transition处理状态切换的平滑过渡是更合适的方案,以下是修改后的完整代码:
修改后的CSS代码
/* 父容器设置相对定位,作为滑块的定位基准 */ .toggle-container { position: relative; width: 70px; height: 40px; } #spherewishlist { height: 40px; width: 70px; background-color: gray; border-radius: 40px; display: block; border: 2px solid white; /* 修正border-color不生效问题,直接使用border属性 */ transition: background-color 1s ease; /* 同步轨道颜色的过渡动画 */ } #circlewishlist { height: 36px; width: 40px; background-color: white; border-radius: 100%; display: block; box-shadow: 0px 1px 1px #141414; position: absolute; /* 改用绝对定位,基于父容器定位 */ left: 3px; /* 默认初始位置 */ top: 2px; /* 垂直居中滑块 */ content: url('white-circle-frame-with-shadow-free-png.png'); appearance: none; cursor: pointer; /* 添加鼠标指针,提升交互体验 */ transition: left 1s ease; /* 核心:添加位置变化的过渡动画 */ } #circlewishlist:checked { left: 27px; /* 勾选后的位置(70-40-3=27,确保滑块完全在轨道内) */ } #circlewishlist:checked + #spherewishlist { background-color: green; }
修改后的HTML代码
<div class="toggle-container"> <input id="circlewishlist" type="checkbox"><!-- this is the circle--> <div id="spherewishlist"></div><!-- this is the sphere--> </div>
关键修改说明
- 新增
.toggle-container父容器并设置position: relative,让滑块的绝对定位有基准,避免布局混乱。 - 把滑块的
position: relative改为absolute,配合left属性控制位置,同时添加transition: left 1s ease,让左右滑动都有平滑过渡。 - 移除原有的
animation和@keyframes代码,改用:checked状态直接修改left值,依赖transition实现双向平滑切换。 - 调整滑块的
top值让它垂直居中,修正轨道的border属性确保样式生效,同时给轨道颜色变化也添加了过渡效果,保持整体交互一致性。
内容的提问来源于stack exchange,提问作者Noor
相关产品推荐
相关产品推荐

