CSS切换按钮动画问题:需实现无重复的从左向右移动效果
Hey there! Let's sort out that toggle slider problem where it's moving left instead of right, and get a clean, non-repeating left-to-right animation working properly.
First, let's break down the key issues in your original code:
- Nested
<button>elements are invalid HTML and can cause unexpected behavior. - The
.main-togglelacksposition: relative, so your absolute-positioned.sub-toggleis positioning itself relative to the entire document instead of its parent toggle container. - Your animation only defines a 50% keyframe with
left: 20%, which doesn't land the slider in the correct right-side position, and there's no setup to keep it there after the animation finishes.
Here's the fixed solution using semantic HTML and adjusted CSS to get the smooth, non-repeating animation you want:
HTML
<label class="main-toggle"> <input type="checkbox" class="toggle-input"> <span class="sub-toggle"></span> </label>
CSS
.main-toggle { position: relative; /* Critical: anchors the slider to this container */ display: inline-block; border-radius: 30px; width: 200px; height: 50px; background-color: grey; cursor: pointer; } .toggle-input { opacity: 0; /* Hide the checkbox but keep it functional */ width: 0; height: 0; } .sub-toggle { position: absolute; left: 15px; top: 5px; /* Vertically centers the slider in the 50px tall toggle */ border-radius: 30px; width: 40px; height: 40px; background-color: black; } /* Trigger animation when the toggle is checked */ .toggle-input:checked + .sub-toggle { -webkit-animation: slideRight 1s forwards; animation: slideRight 1s forwards; } /* Keyframe animation for smooth left-to-right movement */ @-webkit-keyframes slideRight { from { left: 15px; } to { left: calc(100% - 40px - 15px); } /* Dynamically calculates right position */ } @keyframes slideRight { from { left: 15px; } to { left: calc(100% - 40px - 15px); } /* Cross-browser support */ }
Key Changes Explained:
- Semantic HTML: Swapped nested buttons for a
<label>and hidden checkbox—this is the standard, valid way to build toggle switches. - Relative Parent: Added
position: relativeto.main-toggleso the slider positions itself correctly inside the toggle container, not the whole page. - Targeted Animation: The animation now moves from the initial
left: 15pxto a calculated right position (usingcalc()to stay responsive if you adjust the toggle width later). - Non-Repeating & Persistent State:
animation-fill-mode: forwardsensures the slider stays in its final position after the animation ends, and the animation only triggers once when the toggle is activated.
内容的提问来源于stack exchange,提问作者Sarvesh
相关产品推荐
相关产品推荐

