使用 CSS 自动添加“必填字段"星号到表单输入 [英] Use CSS to automatically add 'required field' asterisk to form inputs

查看:27
本文介绍了使用 CSS 自动添加“必填字段"星号到表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

克服此代码无法按预期工作的不幸事实的好方法是什么:

<label>名称:</label><输入类型=文本">

<风格>.required input:after { content:"*";}</风格>

在一个完美的世界中,所有必需的 input 都会得到一个小星号,表明该字段是必需的.这个解决方案是不可能的,因为 CSS 是在元素内容之后插入的,而不是在元素本身之后,而是像这样的东西是理想的.在具有数千个必填字段的站点上,我可以将输入前面的星号移动到一行(:after:before),或者我可以移动它到标签的末尾 (.required label:after) 或在标签的前面,或到包含框上的某个位置等...

这很重要,不仅在我改变主意将星号放置在任何位置的情况下,而且对于表单布局不允许星号位于标准位置的奇怪情况也很重要.它还适用于检查表单或突出显示未正确完成的控件的验证.

最后,它不会添加额外的标记.

有没有什么好的解决方案可以兼具不可能代码的全部或大部分优点?

解决方案

这是你的想法吗?

http://jsfiddle.net/erqrN/1/

<输入类型=文本"><风格>.required:在{之后内容:" *";红色;}</风格>

.required:after {内容:" *";红色;}

<label class="required">名称:</label><input type="text">

参见 https://developer.mozilla.org/en-US/docs/Web/CSS/伪元素

What is a good way to overcome the unfortunate fact that this code will not work as desired:

<div class="required">
    <label>Name:</label>
    <input type="text">
</div>

<style>
    .required input:after { content:"*"; }
</style>

In a perfect world, all required inputs would get the little asterisk indicating that the field is required. This solution impossible since the CSS is inserted after the element content, not after the element itself, but something like it would be ideal. On a site with thousands of required fields, I can move the asterisk in front of the input with one change to one line (:after to :before) or I can move it to the end of the label (.required label:after) or in front of the label, or to a position on the containing box, etc...

This is important not just in case I change my mind about where to place the asterisk everywhere, but also for odd cases where the form layout doesn't allow the asterisk in the standard position. It also plays well with validation that checks the form or highlights improperly completed controls.

Lastly, it doesn't add additional markup.

Are there any good solutions that have all or most of the advantages of the impossible code?

解决方案

Is that what you had in mind?

http://jsfiddle.net/erqrN/1/

<label class="required">Name:</label>
<input type="text">

<style>
  .required:after {
    content:" *";
    color: red;
  }
</style>

.required:after {
  content:" *";
  color: red;
}

<label class="required">Name:</label>
<input type="text">

See https://developer.mozilla.org/en-US/docs/Web/CSS/pseudo-elements

这篇关于使用 CSS 自动添加“必填字段"星号到表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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