Snap.svg - Select 第二个文本元素?

Snap.svg - Select second text element?

如何 select 第二个 text 元素?

我试过做类似的事情:

.node text:nth-child(2) 但要么我遗漏了某些东西,要么它不起作用。

我正在使用 Snap.svg 向元素添加文本。

element.text(x, y, 'text');

根据文档,无法将 class 添加到文本元素。

所以:nth-child()伪选择器在直接兄弟之间起作用,这意味着如果children在DOM中不相邻,它将不起作用。在这种情况下,我们可以使用 :nth-of-type(),它不那么严格,并且会在不考虑 DOM 中断的情况下以下一个匹配元素为目标(参见演示)。

来自 MDN:

The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element. More simply stated, the selector matches a number of child elements whose numeric position in the series of children matches the pattern an+b.


:nth-child():nth-of-type 的演示:

.node {
  width:50%;
  float:left;
  border:5px solid #FFF;
  box-sizing:border-box;
}

.text, p {padding:1em;margin: 0; background: #000; color:#FFF;}

.node .text:nth-of-type(3) {
  background:green;
}

.node .text:nth-child(3) {
  color:yellow;
}
<div class="node">
  <div class="text">.text 01</div>
  <div class="text">.text 02</div>
  <div class="text">.text 03</div>
  <div class="text">.text 04</div>
</div>

<div class="node">
  <div class="text">.text 01</div>
  <div class="text">.text 02</div>
  <p>p</p>
  <div class="text">.text 03</div>
</div>

如您在演示中所见,左侧有一系列相同的 children,而在右侧它们被 <p> 标记打断。 :nth-of-type(3) 应用的绿色背景在两个示例中都有效,而 :nth-child(3) 的黄色由于中断而无效。

延伸阅读: