css - Snap.svg - 选择第二个文本元素?

标签 css svg snap.svg

如何选择第二个 text 元素?

我试过做类似的事情:

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

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

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

根据文档,没有办法向文本元素添加类。

最佳答案

所以 :nth-child()伪选择器在直接兄弟之间工作,这意味着如果 child 在 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>

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

进一步阅读:

关于css - Snap.svg - 选择第二个文本元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35658848/

相关文章:

javascript - 如何在 snap.svg 中迭代组的元素/子元素?

SVGPath LinkedList 上的 java.lang.NullPointerException

javascript - Snap.svg 只选择一个路径

html - 如何使用 CSS 将图片的大小从正方形更改为圆形?

php - 使用后期处理上传进度

javascript - 将 SVG 标记从 HTML 页面保存到 SVG 图像

CSS/SVG 创建螺旋

javascript - snapsvg - 在 SVG + 事件中添加 SVG 不起作用

css - Rails - 删除默认样式表

javascript - 推特 Bootstrap 模型