如何定位直接文本而不是标签中的文本? [英] How to target direct text and not text within tags?

查看:73
本文介绍了如何定位直接文本而不是标签中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法只能定位<h1> -Tag中的直接文本?

Is there a way to only target the direct text within a <h1>-Tag?

以下是我想做的事的一个例子:

Here is an example on what I want to do:

<h1>I want to select this text with a css selector <small>but not this text</small></h1>

这似乎不起作用:

h1:not(small)

有可能吗?

推荐答案

h1:not(small)

您的选择器h1:not(small)无效,因为它显示以下内容:

h1:not(small)

Your selector h1:not(small) doesn't work because it says this:

定位所有不是small元素的h1元素.

Target all h1 elements that are not small elements.

与单独使用h1选择器相同.

It's that same as using the h1 selector by itself.

您会更接近h1 :not(small),它说:

定位h1的所有后代,除了small元素.

Target all descendants of an h1 except small elements.

景气!正是您想要的.

除了直接包含在元素内的文本(即,周围没有标签的文本)成为匿名元素之外.并且 CSS无法选择匿名元素.

Except that text contained directly inside an element (i.e, text with no tags around it) becomes an anonymous element. And anonymous elements are not selectable by CSS.

h1 :not(small) {
  color: orange;
}

<h1>This text is contained directly inside the container. It is not selectable by CSS. It is an anonymous element. <small>This text is inside a small element</small></h1>

<hr>

<h1><span>This text is contained in a span. It is selectable by CSS</span> <small>This text is inside a small element</small></h1>

要排除small元素,必须将自己标识为h1的子元素.

For the small element to be excluded it would have to identify itself as a child of the h1.

但是 CSS中没有父选择器.

您需要两个选择器才能使这项工作:

You need two selectors to make this work:

  • 第一个在父级上设置样式.
  • 第二个替代子项上的第一个.

h1 {
  color: orange;
}

h1 > small {
  color: black;
}

<h1>I want to select this text with a css selector <small>but not this text</small></h1>

  • Targeting text nodes with CSS
  • Is it possible to style anonymous flex items explicitly?
  • Is it possible to select elements not preceded by text?

这篇关于如何定位直接文本而不是标签中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆