【问题标题】:Matching the first/nth element of a certain type in the entire document匹配整个文档中某种类型的第一个/第n个元素
【发布时间】:2015-02-15 22:22:04
【问题描述】:

如何指定整个文档的:first-of-type

我想为 HTML 的第一个 <p> 设置样式,无论它位于何处(我不想写 section p:first-of-type,因为它可能位于不同 HTML 文档的其他位置)。

p {
  background:red;	
}

p:first-of-type {
  background:pink;
}

p:last-of-type {
  background:yellow;	
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

【问题讨论】:

  • 你能不能只给第一个类并分配css?
  • 恐怕用纯CSS是不可能实现的。你必须用 JavaScript 弄脏你的手:-)
  • 您介意重新表述您的问题吗...我不确定我是否理解正确...在示例中,您给出了您要达到的颜色顺序?
  • 您在寻找选择器* 吗?
  • @henser 问题很清楚,OP 想要定位第一个段落元素,无论它位于文档中的哪个位置。

标签: html css css-selectors


【解决方案1】:

不幸的是,仅使用 CSS 是不可能的。 :first-of-type伪类states的文档:

:first-of-type 伪类表示一个元素,它是其父元素的子元素列表中其类型的第一个兄弟元素。

这意味着:first-of-type 应用于其类型的第一个元素,相对于其父元素,而不是文档的根(或body 元素,在这种情况下)。


JavaScript 解决方案

:first-of-type

我们可以通过引入一些 JavaScript 来实现这一点。为此,我们只需要 JavaScript 的 querySelector() 方法,该方法从指定的选择器中提取第一个匹配元素。

在此示例中,我将您的 :first-of-type 伪类更改为“first-of-type”类,然后使用 JavaScript 将此类添加到使用 querySelector('p') 时返回的元素中:

document.querySelector('p').className += ' first-of-type';
p {
  background:red;	
}


p.first-of-type {
  background: pink;
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

:nth-child:last-of-type

对于:nth-child:last-of-type,我们可以改用JavaScript 提供的类似方法:querySelectorAll()。此方法将 所有 匹配元素拉入 NodeList(类似于数组),然后我们可以通过索引遍历或从内部选择特定元素:

var elems = document.querySelectorAll('p');

// nth-of-type = NodeList[n - 1]
// e.g. to select the 3rd p element ("333"):
if (elems.length >= 2)
   elems[2].className += ' nth-of-type';

// last-of-type = NodeList length - 1
if (elems.length)
   elems[elems.length - 1].className += ' last-of-type';
p {
  background:red;	
}


p.nth-of-type {
  background: pink;
}

p.last-of-type {
  background: yellow;
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

请注意,我在两个选择器周围都包含了if 语句,以确保 elems NodeList 有足够的元素,否则会引发错误。

【讨论】:

  • 为了最快的解决方案,我也喜欢js,不要浪费时间搜索,改用js
  • 要获取第 n 个匹配元素,只需索引 querySelectorAll:var elements = document.querySelectorAll('p'); elements[elements.length - 1].className += ' last';
  • @BoltClock 似乎我完全忽略了回答这部分问题!我会更新我的答案。
  • 这个功能是否有可能被添加到 CSS4 规范中?
  • @Vandervals 基于Selectors Level 4 工作草案的当前状态,它看起来不像是不幸添加的东西。
猜你喜欢
  • 1970-01-01
  • 2017-12-31
  • 2019-09-16
  • 2015-06-05
  • 2013-12-08
  • 2012-11-18
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多