jQuery / CSS选择复选框标签

时间:2018-05-02 14:45:36

标签: javascript jquery html css forms

我使用带有2个标签的复选框,第1个包含标签文本,第2个是带样式的复选框。



form div.confirm label:first-of-type {
  background: rgba(82, 65, 65, 1);
  color: #FFF;
}

form div.confirm [type=checkbox]:checked.error+label::before {
  background: #4caf50 !important;
}

  <form method="post" id="entryform">
    <div class="w2">
      <label for="addr">Address*:</label>
      <input type="text" name="addr" id="addr" />
    </div>
    <div class="w1 confirm">
      <label for="confirmfinal">I can confirm that...</label>
      <div class="checkcheck">
        <input type="checkbox" value="1" id="confirmfinal" name="confirmfinal" />
        <label for="confirmfinal"></label>
      </div>
    </div>
<div id="submitBlock" class="w1 confirm">
        <input type="submit" name="Submit entry form" class="formbutton" value="Submit entry form">
      </div>
</form>
&#13;
&#13;
&#13;

如何编写CSS选择器,以便在复选框具有.error类时为第一个标签设置样式?

我从这里包含的片段中尝试过CSS,但我似乎错了。我只是想在必要时将标签的背景设置为红色。

提前致谢

1 个答案:

答案 0 :(得分:1)

你不能用直接的CSS做到这一点,但你可以用一点JavaScript / JQuery:

$(".error").on("click", function(){
  if(this.checked){
    $("label[for='confirmfinal']").addClass("error");
  } else {
    $("label[for='confirmfinal']").removeClass("error");  
  }
});
form div.confirm label:first-of-type {
  background: rgba(82, 65, 65, 1);
  color: #FFF;
}

form div.confirm [type=checkbox]:checked.error+label::before {
  background: #4caf50 !important;
}

.error {
 font-weight:bold; color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w1 confirm">
  <label for="confirmfinal">I can confirm that...</label>
  <div class="checkcheck">
    <input type="checkbox" value="1" id="confirmfinal" name="confirmfinal" class="error">
    <label for="confirmfinal"></label>
  </div>
</div>