需要HTML5输入,在提交时滚动到带有固定navbar的输入 [英] HTML5 input required, scroll to input with fixed navbar on submit

查看:185
本文介绍了需要HTML5输入,在提交时滚动到带有固定navbar的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试提交缺少必填字段的表单时,我的浏览器(Chrome)会显示一条消息,提示您缺少某个字段,如果该字段不在我的屏幕上,则会向上滚动到该字段。

When trying to submit a form with missing required fields, my browser (Chrome), displays a message mentionning there is a field missing, and if it's out of my screen, it scrolls up to it.

我的问题是,我的网页中有一个50px的固定标题,因此,输入字段被隐藏,并且消息似乎无处不在:

My problem is that I have a 50px fixed header in my webpage, and as a result, the input field is hidden, and the message seems to come out of nowhere:

而不是

有办法吗?

我尝试了对< html> body>

干杯

EDIT

这里有一个小问题: http ://jsfiddle.net/LL5S6/1/

推荐答案

我发现的唯一方法是添加override '到无效处理程序。
要在表单中的每个输入上实现这一点,你可以这样做。

The only way I found is adding an 'override' to the invalid handler. To implement this for every input in your form you can do something like this.

var elements = document.querySelectorAll('input,select,textarea');
var invalidListener = function(){ this.scrollIntoView(false); };

for(var i = elements.length; i--;)
    elements[i].addEventListener('invalid', invalidListener);

这需要HTML5,并且已在IE11,Chrome和Firefox上测试。

注册@HenryW找到 scrollIntoView 工作原理像预期。

This requires HTML5 and this is tested on IE11, Chrome and Firefox.
Credits to @HenryW for finding that scrollIntoView works like expected.

请注意false参数 scrollIntoView 将输入与底部对齐,因此如果您有一个大的形式,它可能会与页面底部对齐。

Note that the false parameter for scrollIntoView aligns the input with the bottom, so if you have a large form it may be aligned with the bottom of the page.

这篇关于需要HTML5输入,在提交时滚动到带有固定navbar的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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