如何判断浏览器是否已自动填充文本框?特别是用户名和密码框,自动填充页面加载。
我的第一个问题是,这在页面加载序列中什么时候发生?是在document.ready之前还是之后?
其次,我如何使用逻辑来找出是否发生了这种情况?这不是我想阻止这种情况发生,只是挂钩到事件。最好是这样的:
if (autoFilled == true) {
} else {
}
如果可能的话,我很想看到一个jsfiddle显示你的答案。
可能重复
DOM事件浏览器密码自动填充?
浏览器自动填充和Javascript触发事件
这两个问题都没有真正解释什么事件被触发,它们只是不断地重新检查文本框(对性能不好!)
从我个人的经验来看,下面的代码在firefox IE和safari中工作得很好,但在chrome中选择自动完成时工作得不太好。
function check(){
clearTimeout(timeObj);
timeObj = setTimeout(function(){
if($('#email').val()){
//do something
}
},1500);
}
$('#email').bind('focus change blur',function(){
check();
});
下面的代码工作得更好,因为它会触发每次用户点击输入字段,从那里你可以检查输入字段是否为空。
$('#email').bind('click', function(){
check();
});
我为angularjs找到了一个有效的解决方案。
诀窍是在以下情况下禁用输入字段的required属性
该指令检测字段是由浏览器通过自动填充填充的。
由于不再需要输入字段,登录提交按钮将被启用。
这即使用户没有点击进入窗口的主体(见Chrome自动填充/自动完成无值密码)。
指令:
angular.module('formtools').directive('autofill', [
'$interval', function ($interval)
{
return {
scope: false,
require: 'autofill',
controller: function AutoFillController(){
this.applied = false;
},
controllerAs: 'autoFill',
link: function (scope, elem, attrs, autofill)
{
var refresh = $interval(function() {
// attention: this needs jquery, jqlite from angular doesn't provide this method
if(elem.is(':-webkit-autofill'))
{
autofill.applied = true;
$interval.cancel(refresh);
}
}, 100, 100);
}
}
}]);
HTML:
<form name="loginform">
<input
type="text"
name="username"
autofill
ng-required="!autoFill.applied">
<input
type="password"
name="password"
autofill
ng-required="!autoFill.applied">
<button ng-disabled="loginform.$invalid">Login</button>
</form>
我也在找类似的东西。Chrome只有……在我的例子中,包装器div需要知道输入字段是否被自动填充。所以我可以给它额外的css就像Chrome在自动填充时对输入字段所做的那样。通过查看以上所有的答案,我的综合解决方案如下:
/*
* make a function to use it in multiple places
*/
var checkAutoFill = function(){
$('input:-webkit-autofill').each(function(){
$(this).closest('.input-wrapper').addClass('autofilled');
});
}
/*
* Put it on the 'input' event
* (happens on every change in an input field)
*/
$('html').on('input', function() {
$('.input-wrapper').removeClass('autofilled');
checkAutoFill();
});
/*
* trigger it also inside a timeOut event
* (happens after chrome auto-filled fields on page-load)
*/
setTimeout(function(){
checkAutoFill();
}, 0);
这个工作的html将是
<div class="input-wrapper">
<input type="text" name="firstname">
</div>