控制复选框的标签

Label to control checkbox

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

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

我的 css 选择器适合这个隐藏的输入吗?我可能遗漏了一些简单的东西。

.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;
}
<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>

问题出在这个选择器上:input[type=checkbox]:checked+label

这意味着您正在定位紧跟在您输入之后的标签 (element+element)。 问题是你的隐藏 inputcheckboxlabel 之间。

如果你把你的隐藏 input :

  • 在你的 checkbox
  • 之前
  • 在你的 label
  • 之后
  • 在你的 label.
  • 里面

Live Demo with 3 hidden inputs


更新 1:

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

将元素移动 jquery

这会将隐藏的输入移到您的复选框之前

Updated exemple