标签控制复选框

时间:2015-04-02 14:01:18

标签: html5 css3 checkbox

我一直在使用CSS hack来使用<label for=""..来控制复选框的切换。这是codepen

当我添加另一个<input>时,它会禁用该复选框的切换。 (当我删除隐藏的输入时一切正常)..

我的css选择器是否适应这种隐藏的输入?我可能会遗漏一些简单的东西。

&#13;
&#13;
.checkbox-on-off {
  position: relative;
  display: inline-block;
  width: 35px;
  padding-right: 2px;
  overflow: hidden;
  vertical-align: middle;
    margin-top: 10px;
}

/* this positions the check box label over the text box */
.checkbox-on-off input[type=checkbox] {
  position: absolute;
  opacity: 0;
}

/* makes the background blue */
.checkbox-on-off input[type=checkbox]:checked+label {
  background-color: #167ac6;
}
/* this is the grey background check mark */
.checkbox-on-off label {
  display: inline-block;
  border: 1px solid transparent;
  height: 15px;
  width: 100%;
  background: #b8b8b8;
  cursor: pointer;
  border-radius: 20px;
}

/* this adds / positions the check mark */
.checkbox-on-off input[type=checkbox]:checked+label .checked {
  display: inline-block;
  margin-top: 3px;
  margin-left: 6px;
  background-size: auto;
  width: 10px;
  height: 10px;
}

/* if you click the checkbox, it sometimes has a grey square */
.checkbox-on-off label .checked {
  display: none;
}

.checkbox-on-off input[type=checkbox]:checked+label .unchecked {
  display: none;
}

.checkbox-on-off label .unchecked {
  display: inline-block;
  float: right;
  padding-right: 3px;
}


#autoplay-checkbox-label
.checkbox-on-off label {
  display: inline-block;
  border: 1px solid transparent;
  height: 13px;
  width: 100%;
  background: #b8b8b8;
  cursor: pointer;
  border-radius: 20px;
}

/* this positions the white dot */
.checkbox-on-off input[type=checkbox]:checked+label .toggle {
  float: right;
}

/* this is the actual white dot */
.checkbox-on-off label .toggle {
  float: left;
  background: #fbfbfb;
  height: 15px;
  width: 13px;
  border-radius: 20px;
}
&#13;
<span class="checkbox-on-off ">
    <input id="autoplay-checkbox" class="" type="checkbox" checked="">
    <input name="" type="hidden" value="false">
    <label for="autoplay-checkbox" id="autoplay-checkbox-label">
        <span class="checked">&nbsp;</span>
        <span class="unchecked"></span>
        <span class="toggle">&nbsp;</span>
    </label>
</span>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

问题来自此选择器:input[type=checkbox]:checked+label

这意味着您正在定位输入后的标签(element+element)。 问题是您隐藏的input介于checkboxlabel之间。

如果您放置隐藏的input

,一切正常
  • checkbox
  • 之前
  • label
  • 之后
  • label
  带有3个隐藏输入的

Live Demo


更新1:

如果您无法修改HTML标记,可以通过添加$("input[type=hidden]").prependTo("#autoplay-checkbox");

按jquery移动元素

这将在复选框

之前移动隐藏的输入
  

Updated exemple

相关问题