首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Delay HTML5 :在第一个事件之前无效的伪类

Delay HTML5 :在第一个事件之前无效的伪类
EN

Stack Overflow用户
提问于 2011-10-28 02:43:29
回答 11查看 40K关注 0票数 84

我最近发现,只要页面加载,:invalid伪类就会应用于required表单元素。例如,如果你有这样的代码:

<style>
input:invalid { background-color: pink; color: white; }
input:valid { background-color: white; color: black; }
</style>
…
<input name="foo" required />

然后,您的页面将加载一个空的粉红色输入元素。在HTML5中内置验证是很棒的,但我认为大多数用户在有机会输入任何值之前都不希望表单进行验证。有没有办法将伪类的应用推迟到影响该元素的第一个事件(表单提交、模糊、更改,任何适当的事件)?有没有可能在没有JavaScript的情况下做到这一点?

EN

回答 11

Stack Overflow用户

发布于 2018-01-08 11:52:23

这些答案已经过时了。现在,您可以使用CSS检查占位符伪类。

input:not(:placeholder-shown):invalid {
    background-color: salmon;
}
form:invalid button {
    background-color: salmon;
    pointer-events: none;
}
<form>
    <input type="email" placeholder="me@example.com" required>
    <button type="submit">Submit</button>
</form>

它从正常的背景开始,当你在其中输入不完整的电子邮件地址时,它会变成粉色。

票数 37
EN

Stack Overflow用户

发布于 2013-06-29 00:25:50

这在纯CSS中是不可能的,但可以使用JavaScript来完成。这是一个jQuery example

// use $.fn.one here to fire the event only once.
$(':required').one('blur keydown', function() {
  console.log('touched', this);
  $(this).addClass('touched');
});
/**
 * All required inputs initially are yellow.
 */
:required {
  background-color: lightyellow;
}

/**
 * If a required input has been touched and is valid, it should be white.
 */
.touched:required:valid {
  background-color: white;
}

/**
 * If a required input has been touched and is invalid, it should be pink.
 */
.touched:required:invalid {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <label>
    Name:
    <input type="text" required> *required
  </label>
</p>
<p>
  <label>Age:
    <input type="text">
  </label>
</p>

票数 26
EN

Stack Overflow用户

发布于 2018-06-30 06:51:18

Mozilla用他们自己的:-moz-ui-invalid伪类来解决这个问题,这个伪类只在表单与之交互后才会应用。由于缺乏支持,MDN不建议使用此功能。但是,您可以为Firefox修改它。

在地平线上有一个:user-invalid规范的4级规范,它将提供类似的行为。

如果这没有帮助,我很抱歉,但我希望它能提供一些背景。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7920742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档