我有一个 HTML 5 表单!太好了,我很兴奋!我决定使用 xmlHttpRequest 提交表单,我正在使用 jQuery,所以 $.post(...)
。它有效,太棒了。我输入了一些无效数据并提交了表单,这些表单控件的有效性状态无效 - 正如预期的那样。到目前为止一切顺利。
现在我在表单的输入控件中输入有效值并再次提交表单,这次成功了,除了一件事,在调用表单的 reset()
方法后,红色框阴影样式仍然存在.但是,如果输入在与它们交互后处于无效状态,但在提交表单之前被更正为有效状态,则当调用表单的 reset()
方法时,样式将被删除。
所以问题是如何覆盖这种行为?
最佳答案
Mozilla Firefox 将伪类 :-moz-ui-invalid
应用于任何无效的表单控件。如果表单从未提交过,或者如果在调用表单的 submit()
方法时所有表单输入控件都有效,则调用表单的 reset()
方法将导致伪类从输入控件中删除。
但是,如果在提交表单时任何表单的输入控件无效,则伪类将始终应用无效的输入控件,即使在重置表单后也是如此。
如需完整文档和下载注释的 javascript 文件,请访问:http://www.syn-to.com/moz-ui-invalid.php
var form;
(function()
{
"use strict";
//name must be a valid form name eg. <form name="myFormName" ...
form = function(name)
{
var a =
{
"registerReset": function()
{
//if the boxShadow property exists, bind the reset event handler
//to the named form
if(typeof document.forms[name].style.boxShadow !== 'undefined')
{
document.forms[name].addEventListener('reset', a.resetEventHandler);
}
},
"reset": function()
{
a.registerReset();
document.forms[name].reset();
},
"resetEventHandler": function()
{
//override the default style and apply no boxShadow and register
//an invalid event handler to each of the form's input controls
function applyFix(inputControls)
{
for(var i=0;i<inputControls.length;i++)
{
inputControls[i].style.boxShadow = 'none';
inputControls[i].addEventListener('invalid', a.invalidEventHandler);
inputControls[i].addEventListener('keydown', a.keydownEventHandler);
}
}
var inputControls = this.getElementsByTagName('input');
applyFix(inputControls);
var inputControls = this.getElementsByTagName('textarea');
applyFix(inputControls);
var inputControls = this.getElementsByTagName('select');
applyFix(inputControls);
},
"invalidEventHandler": function()
{
this.style.boxShadow = '';
this.removeEventListener('invalid', a.invalidEventHandler);
this.removeEventListener('keydown', a.keydownEventHandler);
},
//the following functions emulates the restore of :-moz-ui-invalid
//when the user interacts with a form input control
"keydownEventHandler": function()
{
this.addEventListener('blur', a.blurEventHandler);
},
"blurEventHandler": function()
{
this.checkValidity();
this.removeEventListener('blur', a.blurEventHandler);
}
};
return a;
}
})();
用法:
在 native 重置之前必须调用以下两种方法之一(调用表单的 reset()
方法):
<form name="formName" ...>...</form>
form('formName').registerReset(); //registers the event handlers once
form('formName').reset(); //registers the event handlers at the time reset is called
//and then calls the form's native reset method, may be used
//in place of the native reset
在我看来,无论是否使用 ajax,也无论用户之前是否尝试提交带有无效输入控件的表单,重置都应该删除该样式!我已经提交了一个错误报告,但到目前为止它还不被认为是一个错误:https://bugzilla.mozilla.org/show_bug.cgi?id=903200
这应该也能帮助其他人。
关于javascript - 重置 HTML 5 表单 Firefox 后,红色边框仍出现在输入中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171381/