Webkit内核的浏览器有一个-webkit-autofill
私有属性,
通过审查元素可以看到这是由于chrome会默认给自动填充的input表单加上input:-webkit-autofill私有属性,然后对其赋予以下样式:
input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill {
background-color: rgb(250, 255, 189); /* #FAFFBD; */
background-image: none;
color: rgb(0, 0, 0);
}
因此我们就会想到覆盖这个样式,代码如下,但是依然不能覆盖原有的背景、字体颜色。需要注意的是:加 !important
依然不能覆盖原有的背景、字体颜色,除了chrome默认定义的background-color
,background-image
,color
不能用!important
提升其优先级以外,其他的属性均可使用!important
提升其优先级。
input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill {
background-color: #FFFFFF;
background-image: none;
color: #333;
/* -webkit-text-fill-color: red; //这个私有属性是有效的 */
}
input:-webkit-autofill:hover {
/* style code */
}
input:-webkit-autofill:focus {
/* style code */
}
情景一:input文本框是纯色背景的
解决办法:
input:-webkit-autofill {
-webkit-box-shadow: 0 0 0px 1000px white inset;
-webkit-text-fill-color: #333;
}
情景二:input文本框是使用图片背景的
解决办法:
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0)
{
var _interval = window.setInterval(function () {
var autofills = $('input:-webkit-autofill');
if (autofills.length > 0) {
window.clearInterval(_interval); // 停止轮询
autofills.each(function() {
var clone = $(this).clone(true, true);
$(this).after(clone).remove();
});
}
}, 20);
}
下面的js不是太靠谱
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
$(window).load(function(){
$('input:-webkit-autofill').each(function(){
var clone = $(this).clone(true, true);
$(this).after(clone).remove();
});
});
}
思路二: 关闭浏览器自带填充表单功能
设置表单属性 autocomplete="off/on"
关闭自动填充表单,自己实现记住密码
<!-- 对整个表单设置 -->
<form autocomplete="off" method=".." action="..">
<!-- 或对单一元素设置 -->
<input type="text" name="textboxname" autocomplete="off">
网上大部分文章是使用Cookie实现记住用户名、密码。不管是在前端,还是后端都可以实现。本文不对Cookie存储展开讨论。可自行谷歌
其他
stackoverflow.com上面也有类似的回答
Google Chrome form autofill and its yellow background
Override browser form-filling and input highlighting with HTML/CSS
总结
// TODO: 待编辑
自动填充变成透明的话,google下还有另一种曲线救国的方式
:-webkit-autofill {
-webkit-text-fill-color: #fff !important;
transition: background-color 5000s ease-in-out 0s;
}
就是让浏览器颜色过5000s再变,还是蛮有用的
input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 1000px white inset !important;
}
经过测试,这才是最终的答案