问题描述
我最近发现,只要页面加载,:invalid
伪类就会应用于必需的
表单元素。例如,如果您有以下代码:
I recently discovered that the :invalid
pseudo-class applies to required
form elements as soon as the page loads. For example, if you have this code:
<style>
input:invalid { background-color: pink; color: white; }
input:valid { background-color: white; color: black; }
</style>
…
<input name="foo" required />
然后您的页面将加载一个空的粉红色输入元素。对HTML5内置验证非常好,但我认为大多数用户都不希望表单在有机会输入任何值之前进行验证。是否有任何方法可以延迟伪类的应用,直到影响该元素的第一个事件(表单提交,模糊,更改,适合的任何内容)为止?没有JavaScript可以做到这一点吗?
Then your page will load with an empty pink input element on it. Having validation built in to HTML5 is great, but I don't think most users expect the form to validate before they've had a chance to enter any values at all. Is there any way to delay the application of the pseudo-class until the first event affecting that element (form submit, blur, change, whatever's appropriate)? Is it possible to do this without JavaScript?
推荐答案
按照这个逻辑,你的代码看起来像这样...
Following this logic, your code would look something like this...
<style>
input:focus:required:invalid {background-color: pink; color: white;}
input:required:valid {background-color: white; color: black; }
<style>
在这里创建一个小提琴:
Created a fiddle here: http://jsfiddle.net/tbERP/
正如你猜测的那样,正如你从小提琴中看到的那样,这种技巧只会显示元素具有焦点时的验证样式。只要您将焦点移开,样式将会丢失,无论其是否有效。不以任何方式理想。
As you'd guess, and as you'll see from the fiddle, this technique only shows the validation styling when the element has focus. As soon as you move focus off, the styling is dropped, regardless of whether it is valid or not. Not ideal by any means.
这篇关于在第一个事件之前延迟HTML5:无效的伪类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!