事實是,并不能一勞永逸去除谷歌在自動填充表單時的預設樣式。對于浏覽器工具自動添加的樣式,這裡采取算是一種比較怪異的方法。除非你關閉它的表單自動填充功能,那姑且這篇文章可以不看了。
今天在寫賬号登入頁面時,給input表單添加了背景圖檔和圖示,看起來小清新了不少。可是當用chrome登入自動填充,淡黃色輸入框代替了背景樣式,看起來有些怪異。
在自動填充之後,chrome自動填充的樣式如下圖(空白部分背景沒有加上):
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyNwADM1QTM3EDMxITM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
按照以往使用各種插件經驗::>_<:: ,嗯,應該可以用!important提升優先級之後覆寫掉浏覽器的預設樣式吧。事實上,這種方式在使用插件的時候想要改變某些屬性雖然屢試不爽,但是在這裡是不行的。顯然浏覽器預設添加的樣式優先級更高。
這裡介紹這種方法不算太麻煩,對于有圖示的輸入框也同樣适用。局限性是輸入框背景必須是純色的。
這裡是更改完之後的樣式:
來一個簡單點的代碼:
這是原本的表單及樣式,自動填充樣式很怪異。
html
<form>
<input type="text" name="telno" placeholder="請輸入手機号" />
<input type="password" name="pwd" placeholder="請輸入密碼" />
</form>
css
form input{
display: block;
width: px;
height: px;
margin-bottom: px;
border: ;
padding-left: px;
outline:none
}
form{
input:first {
background: url('@{imgBaseUrl}/input-account.png') no-repeat;
}
input:last {
background: url('@{imgBaseUrl}/input-pwd.png') no-repeat;
}
解決方法:
方法還是那種,覆寫掉原本的樣式。但是谷歌的預設樣式三個屬性是不能更改的,是以隻能從别的地方下手。
input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill { background-color: #FFFFFF;
background-image: none;
color: #333;
}
^_^。首先在input外套一個div塊,将原來input的樣式更改到外層div上,是以背景和圖檔也都加在了外層元素中。這樣背景和圖示有了,可是剩下的input單獨顯示一片蛋黃,好像更醜了。
html
<form id="merchant-login">
<div class = "clear_auto" id = "clear_auto">
<input type="text" name="account" placeholder="請輸入手機号" />
</div>
<div class = "clear_auto">
<input type="password" name="pwd" placeholder="請輸入密碼" />
</div>
</form>
是以再對内層的input标簽進行樣式的更改。邊框設為0,高度和行高設為與父元素也就是外層div都相等(這裡我加了margin并且高度比原來小2px是因為原本的背景包含邊框各1px)。接下來是針對谷歌自動填充的樣式了,屬性前加私有字首僅對谷歌生效:
-webkit-box-shadow: 0 0 0px 1000px #d3d3d3 inset; 盒子陰影屬性,設定盒子内陰影顔色,用取色器取原來背景色,1000px直接覆寫掉原來的背景,網上有很多工具,可以自己搜一下。
-webkit-text-fill-color: #000; 設定文本顔色為黑,這個不多說。
多說一句:first和:last僞元素選擇器,因為加了div之後,兩個input框不屬于同一個父元素,是以兩個分開要在父元素下寫。
less代碼:
form .clear_auto {
display: block;
width: px;
height: px;
margin-bottom: px;
border: ;
padding-left: px;
outline: none;
input {
border: ;
height: px;
line-height: px;
outline: none;
background-color: transparent;
margin-top: px;
}
}
form {
.clear_auto: nth-child(){
background: url('@{imgBaseUrl}/input-account.png') no-repeat;
input: -webkit-autofill {
-webkit-box-shadow: px px #d3d3d3 inset;
-webkit-text-fill-color: #000;
}
}
.clear_auto:nth-child(2) {
background: url('@{imgBaseUrl}/input-pwd.png') no-repeat;
input: -webkit-autofill {
-webkit-box-shadow: px px #DBD7D4 inset;
-webkit-text-fill-color: #000;
}
}
}
是以,對于背景色為純色的表單,這種解決方案,親測,完美。
更多精彩内容請通路:前端部落格