Chrome 自動填充表單時,會強制給 input 套用 :-webkit-autofill 私有偽類,覆蓋背景為 #FAFFBD (淡黃),嚴重破壞設計稿(特別是圖片背景/圓角按鈕)。以下提供分場景解決方案。
input:-webkit-autofill {
background-color: #FAFFBD;
background-image: none;
color: #000;
}
此偽類優先級極高,**無法用 !important 覆蓋 background-color/image/color**。
input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 1000px white inset; /* 超大內陰影覆蓋黃色 */
border: 1px solid #ccc !important; /* 邊框可用 !important */
/* 如有圓角/高度需求,同樣可用 !important */
height: 27px !important;
line-height: 27px !important;
border-radius: 0 4px 4px 0 !important;
}
原理:box-shadow inset 繪製在背景之上、邊框之下,足夠大的擴散半徑 (1000px) 完整覆蓋輸入區域。
現代瀏覽器 border-radius、box-shadow、linear-gradient 可完美替代圖片,且不受 autofill 干擾。
if (navigator.userAgent.includes('Chrome')) {
window.addEventListener('load', () => {
document.querySelectorAll('input:not([type=submit])').forEach(input => {
const clone = input.cloneNode(true);
input.parentNode.replaceChild(clone, input); // 破壞 autofill 綁定
});
});
}
副作用:使用者失去自動填充便利性,體驗下降。
<form autocomplete="off"> ... </form>
或單獨控制:<input autocomplete="off"> (Chrome 34+ 可能忽略,需搭配 autocomplete="new-password" 等技巧)。
background-color + !important:Chrome 30+ 已封鎖,無效。-webkit-box-shadow: 0 0 0 1000px #your-bg-color inset; 解決 95% 純色/漸層背景案例。autocomplete="off" 關閉功能,犧牲便利性換視覺一致。