首页 > 解决方案 > jQuery 每个空的必填字段焦点和滚动顶部

问题描述

当需要一个字段并且字段值为0时,我想专注于该字段。我想通过从顶部滚动来在屏幕中间显示该字段。使用下面的代码滚动无法正常工作....

$('form.cartec').on('submit', function () {
  if ($("input[required]").length > 0){
  $('html , body').animate({
    scrollTop: $("input[required]").focus().offset().top-30
  }, 2000);
  $("input[required]").focus();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="cartec" action="/action_page.php">

  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required>

  <label for="password">Password:</label>
  <input type="text" id="password" name="password" required>

  <label for="location">Location:</label>
  <input type="text" id="location" name="location" required>

  <label for="brandcolor">Brand Color:</label>
  <input type="text" id="brandcolor" name="brandcolor" required>

  <label for="product-type">Product Type:</label>
  <input type="text" id="product-type" name="product-type" required>

  <input type="submit">
  
</form>

标签: htmljquerycss

解决方案


推荐阅读