:placeholder-shown 伪类的匹配和 placeholder 属性密切相关,顾名思义就是“占位符显示伪类”,表示当输入框的 placeholder 内容显示的,匹配该输入框。
一、实现 Material Design 风格占位符交互效果
这种交互风格,输入框处于聚焦状态时,输入框的占位符内容以动画形式移动到左上角作为标题存在。
现在这种设计在移动端很常见,因为宽度较稀缺。相信不少人在实际项目中实现过这种交互,而且,一定是借助 JavaScript 实现的。
实际上,我们可以借助 CSS:placeholder-shown 伪类(纯 CSS,无任何 JavaScript)实现这样的占位符交互效果。如图所示:
HTML 代码:
<div className={"input-fill-x"}>
<textarea className={"input-fill"} placeholder={"邮箱"}/>
<label className={"input-label"}>邮箱</label>
</div>
CSS 代码:
input {
border: 2px solid gray;
}
input:placeholder-shown {
border: 2px solid black;
}
.input-fill:placeholder-shown::placeholder {
color: transparent;
}
.input-fill-x {
position: relative;
}
.input-label {
position: absolute;
//left: 16px;
//top: 14px;
left: 0.2%;
top: 2px;
font-size: 0.9em;
pointer-events: none;
}
.input-fill {
padding: 1em;
}
.input-fill:not(:placeholder-shown) ~ .input-label,
.input-fill:focus ~ .input-label {
transform: scale(0.75) translate(0, -1em);
background-color: white;
padding: 0 .2em;
}
学 CSS 选择器过程中,发现很多动效都是可以通过纯 CSS 的伪类特性来实现,这就是往深度学习的乐趣吧。