如何实现多个开关按钮?

时间:2015-01-06 09:15:06

标签: html html5 css3

我创建了一个开关切换,如果我创建了多个开关,它就不能正常工作。

HTML

<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" 
           checked>
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>

<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" 
           checked>
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>

这里是Js Fiddle:http://jsfiddle.net/dgj7s5sk/ 有人帮助我解决这个问题。

3 个答案:

答案 0 :(得分:2)

您不能拥有多个具有相同ID的元素。

将第二个input的ID更改为其他内容(以及for中的label值),以便label知道它们与哪个元素相关到。

这有效:

<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked="checked" />
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch2" checked="checked" />
    <label class="onoffswitch-label" for="myonoffswitch2">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>

答案 1 :(得分:0)

每个“开关切换”必须具有自己的ID。 尝试:

<input type="checkbox" name="onoffswitch1" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
<label class="onoffswitch-label" for="myonoffswitch1">
...
<input type="checkbox" name="onoffswitch2" class="onoffswitch-checkbox" id="myonoffswitch2" checked>
<label class="onoffswitch-label" for="myonoffswitch2">

答案 2 :(得分:0)

使用ID而不是类。除了包裹div之外,为每个元素分配ID。