修改 webkit 瀏覽器(Chrome、Safari、Edge)在自動填入(autocomplete)資料後的樣式

分享:

使用 Webkit 瀏覽器的朋友可能都有遇過這樣的經驗,就是當你是使用瀏覽器記憶的值填入時,像是:

就會看到原本的輸入欄位會多了一個背景顏色,可能是黃色或者像這樣的白色,而如果想要修改這個樣式,可以參考以下做法。

首先要先暸解這個樣式是屬於 -webkit-autofill 的,所以要修改這個樣式選擇器要寫這樣:

input:-webkit-autofill,
input:-webkit-autofill:hover, 
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {

}

如果只想針對 input 欄位就這樣寫就好了:

input:-webkit-autofill{

}

Chrome 預設的樣式是這樣

input:-webkit-autofill{
 background-color:rgb(250, 255, 189) !important;
 background-image:none !important;
 color:rgb(0, 0, 0) !important;
}

但我們沒辦法直接蓋掉像是 background 或 color,而是要用一點小技巧,要用 -webkit-text-fill-color 蓋掉 color 以及用 -webkit-box-shadow 蓋掉 background

input:-webkit-autofill{
  border: 1px solid green;
  -webkit-text-fill-color: green;
  -webkit-box-shadow: 0 0 0px 1000px #000 inset;
  transition: background-color 5000s ease-in-out 0s;
}

參考以上的 css,把顏色替換成你要的就好,而如果不要底色,則是把 box-shadow 顏色設定成 transparent。

設定完成就能變這樣:

或是簡單不要讓使用者使用 autocomplete,也可以像這樣設定:

<input name="q" type="text" autocomplete="off"/> 

參考:
Change Autocomplete Styles in WebKit Browsers

 

課程推薦

和我們交流

加入我們的社群,裡面會有一些技術的內容、有趣的技術梗,以及職缺的分享,歡迎和我們一起討論。