在移動(dòng)端,如果標(biāo)簽和輸入框在一行中顯示,顯示的有點(diǎn)窄。

如果標(biāo)簽和輸入框各占一行顯示,又浪費(fèi)空間。有沒有兩全其美的方案呢?
Material Design 提供了一個(gè)兩全其美的方案。輸入框沒有值時(shí),標(biāo)簽在輸入框中顯示。在輸入框中有值或獲得焦點(diǎn)時(shí),標(biāo)簽在上方顯示。如下圖所示:

解決方案
可以用 CSS 的 :placeholder-shown 偽類可以實(shí)現(xiàn)上面的效果。:placeholder-shown 作用于顯示占位符時(shí)的元素。輸入框在有值或獲得焦點(diǎn)時(shí),不顯示占位符,可以用選擇器 :not(:placeholder-shown) 匹配。下面是具體是實(shí)現(xiàn):
HTML 結(jié)構(gòu):
<div class="input-fill-x">
<input class="input-fill" placeholder="name">
<label class="input-label">name</label>
</div>
第 1 步 隱藏瀏覽器默認(rèn)的 placeholder。
.input-fill:placeholder-shown::placeholder {
color: transparent;
}
第 2 步 設(shè)置: 輸入框顯示占位符時(shí)的樣式。
.input-fill-x {
position: relative;
}
.input-label {
position: absolute;
left: 16px; top: 14px;
pointer-events: none;
}
第 3 步 設(shè)置: 輸入框不顯示占位符(即獲得焦點(diǎn)或有值)時(shí)的樣式。
.input-fill:not(:placeholder-shown) ~ .input-label,
.input-fill:focus ~ .input-label {
transform: scale(0.75) translate(0, -32px);
}
完成~
:placeholder-shown 的兼容性很好。

Can I Use
在項(xiàng)目中用起來吧~
覺得本文對你有幫助。點(diǎn)個(gè)贊,分享給小伙伴們吧~