我最近发现,只要页面加载,:invalid
伪类就会应用于required
表单元素。例如,如果你有这样的代码:
<style>
input:invalid { background-color: pink; color: white; }
input:valid { background-color: white; color: black; }
</style>
…
<input name="foo" required />
然后,您的页面将加载一个空的粉红色输入元素。在HTML5中内置验证是很棒的,但我认为大多数用户在有机会输入任何值之前都不希望表单进行验证。有没有办法将伪类的应用推迟到影响该元素的第一个事件(表单提交、模糊、更改,任何适当的事件)?有没有可能在没有JavaScript的情况下做到这一点?
发布于 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>
它从正常的背景开始,当你在其中输入不完整的电子邮件地址时,它会变成粉色。
发布于 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>
发布于 2018-06-30 06:51:18
Mozilla用他们自己的:-moz-ui-invalid伪类来解决这个问题,这个伪类只在表单与之交互后才会应用。由于缺乏支持,MDN不建议使用此功能。但是,您可以为Firefox修改它。
在地平线上有一个:user-invalid规范的4级规范,它将提供类似的行为。
如果这没有帮助,我很抱歉,但我希望它能提供一些背景。
https://stackoverflow.com/questions/7920742
复制相似问题