首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

:invalid

:invalidCSS伪类选择任何输入内容未能满足输入参数设定的<input><form>元素。这使您可以轻松地将无效的字段设定不同的外观,帮助用户识别和纠正错误。

代码语言:javascript
复制
/* Selects any input element, but only if its current value is invalid */
input:invalid {
  background-color: #ffdddd;
}

语法

代码语言:javascript
复制
:invalid

实例

这个例子提供了一个简单的表单,它在有效时将元素设为绿色,而当元素中内容不满足时则为红色。

HTML

代码语言:javascript
复制
<form>
  <label for="url_input">Enter a URL:</label>
  <input type="url" id="url_input" />
  <br />
  <br />
  <label for="email_input">Enter an email address:</label>
  <input type="email" id="email_input" required/>
</form>

CSS

代码语言:javascript
复制
input:invalid {
  background-color: #ffdddd;
}

form:invalid {
  border: 5px solid #ffdddd;
}

input:valid {
  background-color: #ddffdd;
}

form:valid {
  border: 5px solid #ddffdd;
}
  
input:required {
  border-color: #800000;
  border-width: 3px;
}

input:required:invalid {
  border-color: #C00000;
}

笔记

单选按钮

当组中的任何一个单选按钮(即name属性值相同的单选按钮)是required时,如果组中没有任何按钮被选中,:invalid伪类将应用于所有这些按钮。

Gecko违约

默认情况下,Gecko不会将样式应用于:invalid伪类。然而,它确实将一个样式(使用该box-shadow属性的红色“辉光” )应用于:-moz-ui-invalid伪类,该伪类应用于案例的子集中:invalid

您可以使用以下CSS禁用此行为,或完全覆盖它以改变无效字段的外观。

代码语言:javascript
复制
:invalid {
? box-shadow: none;
}

:-moz-submit-invalid {
? box-shadow: none;
}

:-moz-ui-invalid?{
  box-shadow: none;
}

规范

Specification

Status

Comment

HTML Living StandardThe definition of ':invalid' in that specification.

Living Standard

No change

HTML5The definition of ':invalid' in that specification.

Recommendation

Defines the semantic regarding HTML and constraint validation.

Selectors Level 4The definition of ':invalid' in that specification.

Working Draft

Initial definition

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support (<input>)

10.0

20 (12.10240)

4.0 (2)

10

10.0

5.0

Apply it to <form>

(Yes)

No support

13 (13)

No support

(Yes)

?

Feature

Android

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Basic support

?

(Yes)

4.0 (2)

No support

10.0

5.0

Apply it to <form>

?

No support

13.0 (13)

No support

?

?

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com