【问题标题】:Scroll to the first input error of HTML5 form validation滚动到 HTML5 表单验证的第一个输入错误
【发布时间】:2015-07-29 18:27:08
【问题描述】:

我有一个长表单,表单底部带有提交按钮。我在标有必需属性的表单中有多个输入字段。因此,当前几个输入字段之一留空并且我向下滚动以单击提交时,对于浏览器顶部的第一个错误,错误“请填写此字段”正确出现。但是,我必须一直向上滚动到顶部才能输入输入。如何让它自动向上滚动以关注第一个输入错误?

【问题讨论】:

  • stackoverflow.com/questions/6677035/jquery-scroll-to-element 这里有很好的解释,希望对你有所帮助
  • 我已经在chrome、firefox和opera中测试过这个案例,但是你提到的行为并不存在。它通常会一一关注所需的字段来传递信息。注意:我在 ie v8 上测试过,问题是既没有聚焦也没有给出信息。但我确信它将在最新的 ie 版本上运行。
  • @PHJCJO,你是对的。浏览器努力向上滚动到第一个错误输入。但是,在我的情况下,第一个输入框被固定的导航标题挡住了,所以它是不可见的。所以我想我可以将我的问题改写为当发生错误时如何使用 javascript/jQuery 找到第一个无效的表单字段。
  • 如果第一个输入框不可见,为什么要按要求使用?
  • 不,你误解了我的意思。我的意思是,当浏览器向上滚动时,第一个输入字段隐藏在一个栏下(如果我进一步向上滚动,我会看到它)。所以这仍然不是我想要的。

标签: javascript html validation


【解决方案1】:

使用 jQuery 有一个简单的方法。

$('html, body').animate({
    scrollTop: $("#target-element").offset().top
}, 1000);

如果您不想要动画,请改用.scrollTop()

$('html, body').scrollTop($("#target-element").offset().top);

来源:http://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2/

如果您反对 jQuery,您可以使用 window.scrollTo() 推出自己的解决方案

【讨论】:

    【解决方案2】:

    请避免使用动画功能,因为它需要时间来关注元素,但气球首先出现所以最好的方法是这样做。

    function scrollToInvalid(form) {
    var navbar = $('.nav-wrapper');
    
    // listen for `invalid` events on all form inputs
    form.find(':input').on('invalid', function(event) {
        var input = $(this)
    
        // the first invalid element in the form
        var first = form.find(':invalid').first()
    
        // only handle if this is the first invalid input
        if (input[0] === first[0]) {
            // height of the nav bar plus some padding
            var navbarHeight = navbar.height() + 50
    
            // the position to scroll to (accounting for the navbar)
            var elementOffset = input.offset().top - navbarHeight
    
            // the current scroll position (accounting for the navbar)
            var pageOffset = window.pageYOffset - navbarHeight
    
            // don't scroll if the element is already in view
            if (elementOffset > pageOffset && elementOffset < pageOffset + window.innerHeight) {
                return true
            }
    
            // note: avoid using animate, as it prevents the validation message displaying correctly
            $('html,body').scrollTop(elementOffset)
        }
    });
    }
    // call it like this
    var form = $('#contact-form')   //your form element
    scrollToInvalid(form);
    

    【讨论】:

    • 写得很好的答案。我在我的最终解决方案中使用了这个确切的代码,经过轻微修改以匹配我们的内部代码风格。
    【解决方案3】:

    您可以在表单元素附近(之前或之后)添加&lt;a&gt; 元素。当出现验证问题时,您可以点击表单元素旁边的链接。

    如果你给一个&lt;a&gt; 元素起一个名字,比如;

    <a name="anchor"></a>
    

    然后您可以通过;

    转到该位置
    <a href="#anchor"></a>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多