我有以下情况:
<input type="hidden">
<input type="text">
<input type="hidden">
<input type="text">
<input type="text">
<input type="text">
<input type="hidden">
<input type="submit">
如何只选择前两个输入
[type="text"]
?
正如您在这里看到的,第一个 input[type="text"]
的样式不是我需要的。
最佳答案
尽管它们的名字可能暗示什么,:first-of-type
和 :nth-of-type()
不考虑类型
input
元素上的属性,或任何其他元素上的任何其他属性。它只考虑元素的类型,在所有元素的情况下都是 input
。通过扩展,:first-child
和 :nth-child()
在计数时会考虑同一父项的所有 个子项。因此,这两种伪类都不能用来解决您的问题。
您正在使用 input
元素这一事实使这变得更加困难,因为表单元素的性质具有特殊的系统默认样式,无法使用常规 CSS(或任何 CSS)应用).您的问题能否得到解决取决于您希望将哪种样式应用于前两个 input[type="text"]
元素。
如果您应用的样式不会对默认样式产生不利影响(例如 display: none
),或者您根本不关心默认样式,则使用 general sibling combinator ~
就像我描述的那样 here 和 here 会起作用(注意使用两个 ~
组合器,因为您要设置前两个元素的样式,而不仅仅是第一个元素):
input[type="text"] {
/*
* Apply styles to all input[type="text"].
*/
}
input[type="text"] ~ input[type="text"] ~ input[type="text"] {
/*
* Undo or override styles applied in the first rule for any input[type="text"]
* that follows at least two other input[type="text"].
*/
}
否则,如果您需要为后续元素保留默认样式,则此技术将不起作用,因为您无法在修改后恢复默认样式。在这种情况下似乎没有解决方案。
关于html - :first-of-type selector for input type ="text",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24777453/