萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

Chrome 表單自動填充導致 input 背景變黃色問題完美解決方案

Chrome 自動填充表單時,會強制給 input 套用 :-webkit-autofill 私有偽類,覆蓋背景為 #FAFFBD (淡黃),嚴重破壞設計稿(特別是圖片背景/圓角按鈕)。以下提供分場景解決方案。

Chrome 自動填充預設樣式

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) 完整覆蓋輸入區域。

情境二:圖片背景輸入框 — 兩種妥協方案

方案 A:放棄圖片背景,改用 CSS3 模擬 (漸層/圓角/陰影)

現代瀏覽器 border-radius、box-shadow、linear-gradient 可完美替代圖片,且不受 autofill 干擾。

方案 B:犧牲自動填充功能,JS 重建輸入框 (不推薦)

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 綁定
    });
  });
}

副作用:使用者失去自動填充便利性,體驗下降。

方案 C:關閉表單自動填充 (最徹底)

<form autocomplete="off"> ... </form>

或單獨控制:<input autocomplete="off"> (Chrome 34+ 可能忽略,需搭配 autocomplete="new-password" 等技巧)。

網傳失效方案驗證

  • 直接重寫 background-color + !important:Chrome 30+ 已封鎖,無效。
  • jQuery 取值/移除/重插:無法讀取 autofill 填入的 value (存在 DocumentFragment),移除後值消失。

最佳實踐總結

  1. **優先重設計**:改用 CSS3 純樣式輸入框,根除圖片背景被覆蓋問題。
  2. **次優內陰影覆蓋**:-webkit-box-shadow: 0 0 0 1000px #your-bg-color inset; 解決 95% 純色/漸層背景案例。
  3. **最後手段**:autocomplete="off" 關閉功能,犧牲便利性換視覺一致。
copyright © 萬盛學電腦網 all rights reserved