验证表单时,如何滚动到第一个错误而不是跳转?

Her*_*key 48 jquery scrollto jquery-validate

我已经看到很多关于这个主题的变化的问题,但我正在寻找直接的解决方案:

HTML表单,jQuery验证,需要多个字段.提交表单时,验证会跳转到第一个错误并突出显示它.为了提高可用性,我想滚动到第一个错误字段.但它不断完全破坏验证或抛出scrollTo错误.

我需要使用标准验证插件(http://docs.jquery.com/Plugins/Validation),但任何卷轴都没问题,因为我一直在尝试使用scrollTo(http://flesler.blogspot.com/2007/ 10/jqueryscrollto.html).

示例代码位于http://jsfiddle.net/DtgKQ/1/,任何帮助表示赞赏.

Did*_*hys 118

这是你可以做的:

  • 默认情况下,验证插件会聚焦第一个错误元素(如果有的话).focusInvalid通过将其设置为关闭该选项false.

  • invalidHandler当表单无效时,将执行回调处理程序.您可以通过第二个参数访问validator验证器对象,从而访问errorList数组.然后,您可以相对于第一个错误元素为滚动设置动画.

这是代码:

$("#commentForm").validate({
    focusInvalid: false,
    invalidHandler: function(form, validator) {

        if (!validator.numberOfInvalids())
            return;

        $('html, body').animate({
            scrollTop: $(validator.errorList[0].element).offset().top
        }, 2000);

    }
});
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 想通了:'$(validator.errorList [0] .element).offset().top-20' (7认同)
  • 确实非常好+1 (4认同)
  • 凉!我还建议添加$(validator.errorList [0] .element).focus(); 所以这个领域后来关注 (4认同)
  • (http://stackoverflow.com/a/7557433/5628)如果元素在视口中,则跳过滚动@MikeCauser (4认同)
  • ^最好在动画之后通过将其添加到2000之后的匿名函数来完成 (2认同)

小智 10

我不喜欢所有的jQuery扩展,所以这里是我解决这个问题的方法:

if ($('#MYID').valid()) {
      //dosomething();
} else {
    $('html, body').animate({
         scrollTop: ($('.error').offset().top - 300)
    }, 2000);
}
Run Code Online (Sandbox Code Playgroud)

  • @blackhatmario,它是jQuery Validation插件[.valid()](https://jqueryvalidation.org/valid/)的一部分 (2认同)

小智 7

只需将此代码添加到您的主题javascript:

(function($) {
$(document).ready(function(){
    //bmo scroll to not valid
    $(".wpcf7").on('invalid.wpcf7',function(e){
        $('html, body').animate({
                scrollTop: $(".wpcf7-not-valid").first().offset().top-30
            }, 2000);
    });

});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)


Fat*_*lsa 5

对于使用 HTML5 验证 + Vanilla JavaScript 的任何人:

不是这个问题的直接答案,但由于这是搜索这个问题时出现的主要帖子,我想我会在这里为任何也在寻找的人发布我的解决方案!

我在我的 ReactJS 项目中使用了它,但它也应该可以在使用现代浏览器的任何普通 ES6 JavaScript 设置中工作。

function scrollToInvalid(form) {
  const invalidInputs = Array.from(form.querySelectorAll(':invalid, .is-invalid [, .custom-invalid-selector]'));    // set up so you can use any custom invalid classes you're adding to your elements, as well
  invalidInputs.sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top);                      // sort inputs by offset from top of viewport (handles issues with multi-column layouts, where the first element in the markup isn't necessarily the highest on the page)
  invalidInputs[0].scrollIntoView({ block: 'center', behavior: 'smooth' });                                         // scroll first (top) input into center of view, using smooth animation
}

function handleSubmit(e) {
  const form = e.currentTarget;

  if (form.checkValidity() === false ) {
    // form is invalid, don't submit
    e.preventDefault();
    e.stopPropagation();
    // scroll first invalid input into view
    scrollToInvalid(form);
  }
  else {
    // form is valid, handle submit...
  }
}
Run Code Online (Sandbox Code Playgroud)
<form onSubmit="handleSubmit">
  ...
</form>
Run Code Online (Sandbox Code Playgroud)