表单验证自动滚动修改脚本

Form validation autoscroll modification javascript

本文关键字:修改 脚本 滚动 验证 表单      更新时间:2023-09-26

我正在研究表单的javascript验证。我的问题是,提交表单后,浏览器会自动跳转到空单元格。这不是问题,我喜欢这种方式。我的问题是,我的页面上显示了一个固定的标题,这个标题掩盖了表单字段。有什么办法可以绕过它吗?谢谢!

我遇到了同样的问题并像这样修复它:

事件侦听器绑定:

  $('input').on('invalid',function() {
    scrollToInvalid();
  });

功能:

function scrollToInvalid() {
  //Height of your nav bar with some offset
  var navHeight = $('nav#main').height() + 20;
  // Offset of the first input element minus your nav height
  var firstInvalidPosTop = $('input:invalid').first().offset().top;
  var newScrollPos       = firstInvalidPosTop - navHeight;
  // return true if the invalid element is already within the window view. 
  // If you return false, the validation will stop.
  if (  newScrollPos > (window.pageYOffset + navHeight) && 
        newScrollPos < (window.pageYOffset + window.innerHeight - navHeight)) {
    return true;
  } else {
    // If the first invalid input is not within the current view, scroll to the new position.
    $('html, body').scrollTop(newScrollPos);
  }
};