简介
当涉及到验证前端输入字段的内容时,现在的事情比过去容易得多。我们可以将:Required、:Optional、:Valid和:Valid伪类与HTML5表单验证属性(如Required或Pattern)结合使用,以创建非常吸引人的结果。这些伪类用于输入、文本区域和选择元素。
伪类输入
下面是伪类的工作示例。让我们从这个HTML标记开始:
1<form action="#">
2 <input type="text" placeholder="First Name" required>
3 <input type="email" placeholder="Email" required>
4 <input type="text" placeholder="Nickname">
5 <input type="text" placeholder="Favorite pizza topping">
6</form>
让我们应用以下样式:
1input {
2 border: 2px solid;
3 border-radius: 4px;
4 font-size: 1rem;
5 margin: 0.25rem;
6 min-width: 125px;
7 padding: 0.5rem;
8 transition: background-color 0.5s ease-out;
9}
10input:optional {
11 border-color: gray;
12}
13input:required {
14 border-color: black;
15}
16input:invalid {
17 border-color: red;
18}
结果如下:
[鳄鱼vYELYW]
在上面的demo中,<input type=)
属性,所以现代浏览器只有在输入[Valid Valid时才会将输入设置为
:valid`。
添加:Focus伪类
让我们根据焦点状态设置样式,并根据有效性状态添加背景图像和颜色(仅当输入处于焦点状态时),从而使事情变得更加有趣。我们将使用相同的HTML标记。
以下是我们最新的css:
1input {
2 border: 2px solid;
3 border-radius: 4px;
4 font-size: 1rem;
5 margin: 0.25rem;
6 min-width: 125px;
7 padding: 0.5rem;
8 transition: border-color 0.5s ease-out;
9}
10input:optional {
11 border-color: gray;
12}
13input:required:valid {
14 border-color: green;
15}
16input:invalid {
17 border-color: red;
18}
19input:required:focus:valid {
20 background: url("https://assets.digitalocean.com/labs/icons/hand-thumbs-up.svg") no-repeat 95% 50% lightgreen;
21 background-size: 25px;
22}
23input:focus:invalid {
24 background: url("https://assets.digitalocean.com/labs/icons/exclamation-triangle-fill.svg") no-repeat 95% 50% lightsalmon;
25 background-size: 25px;
26}
上面的css有两个关键变化:
1.INPUT:REQUIRED:VALID
只对_REQUIREDD
_INPUTS设置成功状态。因为从技术上讲,可选
输入总是有效的。
2.只有当输入被聚焦时,才会对其使用`Input:Focus:Valid‘和’Input:Focus:Valid‘。
结果如下:
[codesen alligatorio gOrGPxP]
<$>[注意]您可能会想要添加内容,而不是在输入上使用::BEFORE或::AFTER,但不幸的是,这不可能在INPUT元素上实现。一个诀窍是拥有一个兄弟SPAN元素,该元素根据输入的有效性添加内容。大概是这样的:
输入:焦点:无效+span::之前{...}
。<$>