验证表单后,如何滚动到第一个错误而不是跳转? [英] When form is validated, how to SCROLL to the first error instead of jumping?

查看:671
本文介绍了验证表单后,如何滚动到第一个错误而不是跳转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到许多与此主题有关的问题,但我正在寻找简单的解决方案:

I've seen many questions with variations on this theme, but I'm looking for the straightforward solution:

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

HTML form, jQuery validation, multiple fields are required. When the form is submitted, validation jumps to the first error and highlights it. To increase usability, I want to scroll to that first error field. But it keeps blowing up the validation entirely or throwing scrollTo errors.

我需要使用标准的验证插件(http://docs.jquery.com/Plugins/Validation),但是任何滚动条都可以,因为我一直在尝试使用scrollTo(http://flesler.blogspot.com /2007/10/jqueryscrollto.html).

I need to use the standard validation plugin (http://docs.jquery.com/Plugins/Validation) but any scroller would be fine, tho I had been trying with scrollTo (http://flesler.blogspot.com/2007/10/jqueryscrollto.html).

示例代码位于 http://jsfiddle.net/DtgKQ/1/,我们将为您提供帮助.

Sample code is at http://jsfiddle.net/DtgKQ/1/, any help is appreciated.

推荐答案

您可以执行以下操作:

  • 默认情况下,validate插件将重点放在第一个错误的元素上(如果有的话).通过将选项focusInvalid设置为false来将其关闭.

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

The callback invalidHandler handler is executed when the form is invalid. You get access through the second parameter validator to the validator object and thus to the errorList array. You can then animate the scroll relatively to the first erroneous element.

代码如下:

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

        if (!validator.numberOfInvalids())
            return;

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

    }
});

演示

DEMO

这篇关于验证表单后,如何滚动到第一个错误而不是跳转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆