为空时(使用CSS)在输入文本字段时应用不同的样式?

时间:2022-11-13 18:59:39

For instance, a freshly loaded form contains an <input type="text"> which has a green background colour. Once the user enters a value into the field, I would like it to be coloured blue instead.

例如,新加载的表单包含具有绿色背景颜色的。一旦用户在字段中输入值,我希望它变成蓝色。

Is it possible to accomplish this purely using CSS? I understand there is the input[type='text'][value] selector. However, this does not reflect any changes to the form made by the user after it has finished loading, so if the form loaded with no value, it would remain unchanged regardless of what the user does.

是否有可能纯粹使用CSS来实现这一目标?我知道有输入[type ='text'] [value]选择器。但是,这并不反映用户在完成加载后对表单所做的任何更改,因此如果表单没有加载值,则无论用户做什么,它都将保持不变。

2 个解决方案

#1


11  

You could give the textfield the required attribute:

您可以为textfield指定必需的属性:

<input type="text" required />

and then check for validity with CSS:

然后使用CSS检查有效性:

input:invalid { background: green; }

or the opposite (only different for old browsers):

或者相反(仅针对旧浏览器不同):

input:valid { background: blue; }

#2


1  

You can only do this using JavaScript. Here's an example that uses jQuery.

您只能使用JavaScript执行此操作。这是一个使用jQuery的例子。

If you want to change the background-color on focus only, you can use the aptly named :focus pseudo-selector. Here's an example of this.

如果只想更改焦点上的背景颜色,可以使用恰当命名的:focus伪选择器。这是一个例子。

#1


11  

You could give the textfield the required attribute:

您可以为textfield指定必需的属性:

<input type="text" required />

and then check for validity with CSS:

然后使用CSS检查有效性:

input:invalid { background: green; }

or the opposite (only different for old browsers):

或者相反(仅针对旧浏览器不同):

input:valid { background: blue; }

#2


1  

You can only do this using JavaScript. Here's an example that uses jQuery.

您只能使用JavaScript执行此操作。这是一个使用jQuery的例子。

If you want to change the background-color on focus only, you can use the aptly named :focus pseudo-selector. Here's an example of this.

如果只想更改焦点上的背景颜色,可以使用恰当命名的:focus伪选择器。这是一个例子。