Cant get label and input to work on focus

喜你入骨 提交于 2019-12-23 05:20:12

问题


I want to get the label on top of the input. But when I move it up in the code the CSS Focus styles stop working. On focus the label needs gets bigger. How to fix this? tried everything...

form {
  margin-top: 25px;
}

input {
  
  display:block;
}

form input:focus + label {
  font-size: 1.5em;
}
<form>
  
    <!-- DOESN'T WORK
=====================
-->
  <label for="firstname">First name:</label>
  <input id="firstname" name="firstname" type="text">

  <br>
  
  <!-- WORKS 
=====================
-->
  <input id="lasttname" name="firstname" type="text">
  <label for="lasttname">Last name:</label>


</form>

回答1:


Try to wrap label and input in extra div, and use flex-box:

form {
  margin-top: 25px;
}
form input:focus + label {
  font-size: 1.5em;
}

.form-row {
  display: flex;
  flex-direction: column;
  
  margin-bottom: 8px;
}

.form-row label {
   order: 1;
}

.form-row input {
   order: 2; 
   width: 141px;
}
<form>
  
    <!-- DOESN'T WORK
=====================
-->
  <div class='form-row'>
    <input id="firstname" name="firstname" type="text">
    <label for="firstname">First name:</label>
  </div>

  <!-- WORKS 
=====================
-->
  <input id="lasttname" name="firstname" type="text">
  <label for="lasttname">Last name:</label>


</form>



回答2:


An jQuery solution.

$(function() {
  $('form input[type="text"]').focus(function() {
    $(this).prev('label').css("font-size", "1.5em");
  });
  $('form input[type="text"]').focusout(function() {
    $(this).prev('label').css("font-size", "1em");
  });
});
form {
  margin-top: 25px;
}
form input:focus + label {
  font-size: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>

  <!-- DOESN'T WORK
=====================
-->
  <label for="firstname">First name:</label>
  <input id="firstname" name="firstname" type="text">

  <!-- WORKS 
=====================
-->
  <input id="lasttname" name="firstname" type="text">
  <label for="lasttname">Last name:</label>


</form>


来源:https://stackoverflow.com/questions/36400631/cant-get-label-and-input-to-work-on-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!