【发布时间】:2020-01-10 18:51:48
【问题描述】:
我正在尝试自定义 HTML5 验证的行为。当用户点击提交时,我希望无效字段滚动到页面中间。我的第一次尝试是这样做,但它不起作用:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function () {
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
});
});
https://jsfiddle.net/gib65/j1ar87yq/
Calling scrollIntoView(...) with block center not working
它不起作用,因为默认滚动行为,即立即将无效字段滚动到页面顶部(即不平滑),覆盖了我试图在 scrollIntoView(... ) 选项。
然后我尝试了这个:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function (e) {
e.preventDefault();
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
});
});
https://jsfiddle.net/gib65/527u1cm3
添加 preventDefault() 允许我指定的滚动行为发生。但它也阻止了无效字段的聚焦和验证消息的出现。
所以我的问题是:有没有办法让验证消息在不滚动的情况下弹出?
类似这样的:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function (e) {
e.preventDefault();
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
this.focus();
this.showValidationMessage();
});
});
我尝试过 reportValidity() 但这会触发整个验证过程,这当然会破坏目的(即它将调用覆盖我的自定义滚动的默认滚动)。我也试过 checkValidity() 但这会导致“超出最大调用堆栈大小”,可能是因为它触发了“无效”事件,导致侦听器再次拿起它并无限期重复。
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: javascript jquery html validation scroll