文本输入字段的 CSS 选择器?

2022-01-10 00:00:00 css-selectors forms html css html-input

如何使用 CSS 选择器定位文本"类型的输入字段?

解决方案

input[type=text]

或者,限制表单内的文本输入

表单输入[type=text]

或者,进一步限制为某种形式,假设它具有 id myForm

#myForm input[type=text]

注意:IE6 不支持此功能,因此如果您想为 IE6 开发,请使用 IE7.js(如 Yijiang 建议的那样)或开始为所有文本输入添加类.p>

参考:http://www.w3.org/TR/CSS2/selector.html#attribute-selectors


因为规定默认属性值不能始终可以使用属性选择器进行选择,可以尝试覆盖其他文本输入的标记情况:

input:not([type]),/* 标记中不存在类型属性 */input[type=""],/* 类型属性存在,但为空 */input[type=text]/* 类型被明确定义为'text' */

这仍然会在定义类型但具有无效值并且仍回退到 type=text"时的情况.为了涵盖这一点,我们可以使用选择不是其他已知类型之一的所有输入

input:not([type=button]):not([type=password]):not([type=submit])...

但是这个选择器会很荒谬,而且 列表可能的类型随着向 HTML 添加新功能而不断增长.

注意::not 伪类 只支持从 IE9 开始.

How can I target input fields of type 'text' using CSS selectors?

解决方案

input[type=text]

or, to restrict to text inputs inside forms

form input[type=text]

or, to restrict further to a certain form, assuming it has id myForm

#myForm input[type=text]

Notice: This is not supported by IE6, so if you want to develop for IE6 either use IE7.js (as Yi Jiang suggested) or start adding classes to all your text inputs.

Reference: http://www.w3.org/TR/CSS2/selector.html#attribute-selectors


Because it is specified that default attribute values may not always be selectable with attribute selectors, one could try to cover other cases of markup for which text inputs are rendered:

input:not([type]), /* type attribute not present in markup */
input[type=""],    /* type attribute present, but empty    */
input[type=text]   /* type is explicitly defined as 'text' */

Still this leaves the case when the type is defined, but has an invalid value and that still falls back to type="text". To cover that we could use select all inputs that are not one of the other known types

input:not([type=button]):not([type=password]):not([type=submit])...

But this selector would be quite ridiculous and also the list of possible types is growing with new features being added to HTML.

Notice: the :not pseudo-class is only supported starting with IE9.

相关文章