:valid,:invalid和:required CSS伪类

Let's be honest, form validation with JavaScript can be a real bitch.  On a real basic level, however, it's not that bad.  HTML5 has jumped in to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching a given regular expression.  What some people don't know is that you can style elements base on their required, valid, or invalid values.  Here's how!

老实说,使用JavaScript进行表单验证确实是个real子。 但是,从实际的角度来看,还算不错。 HTML5在某种程度上已经加入,提供了一些属性,使我们可以将字段标记为必填字段,或者仅在匹配给定正则表达式时才有效。 某些人不知道的是,您可以根据元素的必需,有效或无效值设置样式。 这是如何做!

CSS (The CSS)

Each state is colon-separated from the element it's associated with:

每个状态均与与其关联的元素以冒号分隔:


/* basics */
input:required {
	border: 1px solid blue;
}
input:valid {
	border: 1px solid green;
}
input:invalid {
	border: 1px solid red;
}


These pseudo classes are straight forward and useful. Here we're changing only borders, but you could use :before and :after to place text or an image next to each field, representing their state.

这些伪类非常简单和有用。 在这里,我们仅更改边框,但是您可以使用:before:after在每个字段旁边放置文本或图像,以表示其状态。

Being able to style elements based on invalid or valid information is something we've shimmed forever with JavaScript, but now we can do so (to some degree) with pure CSS!

能够基于无效或有效信息设置元素样式是我们使用JavaScript永远无法实现的目标,但是现在我们可以(在某种程度上)使用纯CSS做到这一点!

翻译自: https://davidwalsh.name/valid-pseudo-classes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值