html - :first-of-type selector for input type ="text"

标签 html css css-selectors

我有以下情况:

<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"] 的样式不是我需要的。

DEMO

最佳答案

尽管它们的名字可能暗示什么,:first-of-type:nth-of-type() 不考虑类型 input 元素上的属性,或任何其他元素上的任何其他属性。它只考虑元素的类型,在所有元素的情况下都是 input。通过扩展,:first-child:nth-child() 在计数时会考虑同一父项的所有 个子项。因此,这两种伪类都不能用来解决您的问题。

您正在使用 input 元素这一事实使这变得更加困难,因为表单元素的性质具有特殊的系统默认样式,无法使用常规 CSS(或任何 CSS)应用).您的问题能否得到解决取决于您希望将哪种样式应用于前两个 input[type="text"] 元素。

如果您应用的样式不会对默认样式产生不利影响(例如 display: none),或者您根本不关心默认样式,则使用 general sibling combinator ~就像我描述的那样 herehere 会起作用(注意使用两个 ~ 组合器,因为您要设置前两个元素的样式,而不仅仅是第一个元素):

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/

相关文章:

仅包含文本的 JavaScript/JQuery 单选按钮

html - CSS 链接优先级

xpath - 为 Selenium 自动化测试编写 xpath 和 CSS 定位器/路径

CSS 第一个子元素匹配,不匹配任何子元素

html - 简单的 HTML 帮助

javascript - 为什么我的 src 切换使用 jquery 和左/右 keyup 事件随机中断?

javascript - 如何在 Vue.js 中有条件地显示工具提示?

html - 通过 Excel VBA 使用 JS 登录网站

html - 字体大小会增加按钮音量。什么是正确的行为?

html - 关于在 HTML5 Canvas 背景上叠加两个 div 的问题