着重于Bootstrap 4无法使用的标签元素

时间:2018-10-01 10:08:50

标签: jquery bootstrap-4 label focus version

当您关注label字段时,我正在尝试向input添加一个类。我正在使用带有Bootstrap 4的jQuery 1.12.4。

$(function() {
  $('form :input').focus(function() {
    $('label[for="' + this.id + '"]').addClass('labelfocus');
  }).blur(function() {
    $('label[for="' + this.id + '"]').removeClass('labelfocus');
  })
});
.labelfocus { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form class="needs-validation" novalidate>
  <div class="form-group row">
    <div class="col-md-7">
      <label for="firstName">* First Name</label>
      <div class="input-group">
        <input type="text" name="firstName" class="form-control" required>
        <div class="valid-feedback">Great! You've done it.</div>
        <div class="invalid-feedback">Please add your first name.</div>
      </div>
    </div>
  </div>
</form>

1 个答案:

答案 0 :(得分:2)

您需要在输入字段中添加一个ID。 for属性链接到输入的id属性。

这是一个可行的示例:

$(function () {
    $('form :input').focus(function() {
        $('label[for="' + this.id + '"]').addClass('labelfocus');
    })
    .blur(function() {
        $('label[for="' + this.id + '"]').removeClass('labelfocus');
    })
});
.labelfocus {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form class="needs-validation" novalidate>
<div class="form-group row">
    <div class="col-md-7">
        <label for="firstName">* First Name</label>
        <div class="input-group">
            <input type="text" name="firstName" id="firstName" class="form-control" required>
            <div class="valid-feedback">Great! You've done it.</div>
            <div class="invalid-feedback">Please add your first name.</div>
        </div>
    </div>
</div>