4个滑动切换开关功能异常,请求前端技术协助排查
Hey there, let's get those toggle switches working properly for you! The issues are actually just a couple of simple typos that were throwing off the entire layout and functionality, plus a small accessibility tweak to make things more robust.
What Went Wrong
- Misspelled
<label>tag: You used<lable>instead of<label>in your HTML. Browsers don't recognize the misspelled tag, so the.switchstyles weren't being applied to your switch containers. That's why all your switches merged into one unclickable block. - Misspelled CSS position property: In the
.switchclass, you wroteposition: relitiveinstead ofposition: relative. Absolute positioning (like on the.sliderelement) depends on a parent withposition: relativeto anchor itself correctly. Without this, all sliders were positioning relative to the body instead of their individual switch boxes. - Bonus accessibility tweak: Adding unique
idattributes to each checkbox and matchingforattributes on the labels ensures clicks register reliably and makes the switches usable for screen readers.
Fixed Full Code
HTML
<html> <head> <title>Toggle Switch</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <h1>Toggle Switch</h1> <label class="switch" for="toggle1"> <input type="checkbox" id="toggle1"> <span class="slider"></span> </label> <label class="switch" for="toggle2"> <input type="checkbox" checked id="toggle2"> <span class="slider"></span> </label> <label class="switch" for="toggle3"> <input type="checkbox" id="toggle3"> <span class="slider"></span> </label> <label class="switch" for="toggle4"> <input type="checkbox" checked id="toggle4"> <span class="slider"></span> </label> </div> </body> </html>
CSS
* { margin: 0; padding: 0; } .container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } h1 { margin-bottom: 40px; font-family: sans-serif; } .switch { position: relative; /* Fixed the typo here */ display: inline-block; width: 110px; height: 60px; margin: 0 10px; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: 0.4s; border-radius: 34px; } .switch input { display: none; } .slider::before { position: absolute; content: ""; height: 50px; width: 50px; left: 5px; bottom: 5px; background-color: white; transition: 0.4s; border-radius: 50px; } input:checked + .slider { background-color: #ff278c; } input:checked + .slider::before { transform: translateX(50px); }
What You'll See Now
After applying these fixes, you’ll have four side-by-side toggle switches that work perfectly: two start in the "on" position, two in "off", and each will slide smoothly when clicked to toggle states.
内容的提问来源于stack exchange,提问作者James Nelson
相关产品推荐
相关产品推荐

