CSS

:invalid

:invalid

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

/* Selects any input element, but only if its current value is invalid */ input:invalid { background-color: #ffdddd; }

语法

:invalid

实例

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

HTML

<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

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禁用此行为,或完全覆盖它以改变无效字段的外观。

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

规范

SpecificationStatusComment
HTML Living StandardThe definition of ':invalid' in that specification.Living StandardNo change
HTML5The definition of ':invalid' in that specification.RecommendationDefines the semantic regarding HTML and constraint validation.
Selectors Level 4The definition of ':invalid' in that specification.Working DraftInitial definition

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (<input>)10.020 (12.10240)4.0 (2)1010.05.0
Apply it to <form>(Yes)No support13 (13)No support(Yes)?

FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support?(Yes)4.0 (2)No support10.05.0
Apply it to <form>?No support13.0 (13)No support??