延迟 HTML5 : 伪类无效,直到第一个事件 [英] Delay HTML5 :invalid pseudo-class until the first event

查看:22
本文介绍了延迟 HTML5 : 伪类无效,直到第一个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现 :invalid 伪类在页面加载后立即应用于 required 表单元素.例如,如果您有以下代码:

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?

推荐答案

http://www.alistapart.com/articles/forward-thinking-form-validation/

因为我们只想表示一个字段一旦有就无效焦点,我们使用焦点伪类来触发无效的样式.(当然,从一开始就将所有必填字段标记为无效将是一个糟糕的设计选择.)

Since we only want to denote that a field is invalid once it has focus, we use the focus pseudo-class to trigger the invalid styling. (Naturally, flagging all required fields as invalid from the start would be a poor design choice.)

按照这个逻辑,你的代码看起来像这样......

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>

在这里创建了一个小提琴:http://jsfiddle.net/tbERP/

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 : 伪类无效,直到第一个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆