如何获得文本节点的感知样式

How do I get the perceived styling of a text node?

本文关键字:感知 样式 节点 何获得 文本      更新时间:2023-09-26

window.getComputedStyle()方法只接受元素节点是否有任何方法可以可靠地获得确定文本节点视觉表示的样式

我意识到节点不能具有style属性,但它们肯定是样式化的,因为它们继承了父元素的样式。是否有一种方法可以从父元素中获取与文本节点的视觉表示相关的所有计算样式


请注意,将节点封装在span中是不可能的:这将影响CSS规则,如span:nth-childspan + span等。

如果文本节点是元素中仅有节点,则可以简单地在其parentNode上使用getComputedStyle()

但是,请考虑以下内容:

div {border: 1px solid black;}
<div>This <em>is</em> a <strong>test</strong></div>

你不能说"这个"answers"一个"都有边界。说"This"有左上下边框,而"a"只有上下边框是否准确?这是值得怀疑的。

如果您将自己限制为专门应用于文本的样式(颜色、背景、textDecoration、字体等),则在parentNode上应用getComputedStyle()应该始终有效。

我自己试试。

  1. 在父元素上使用window.getComputedStyle(),并存储标记名称和样式信息
  2. 使用存储的标记名称创建一个新元素,并通过style属性为其指定样式
  3. 添加一个子<foo>元素(严格来说,它应该是当前CSS规则中没有提到的标记名,这样它们就不会影响它)
  4. 将父元素附加到文档的<head>(特定于Webkit)
  5. 在子元素上使用window.getComputedStyle()
  6. inline设置为display属性的值(因为文本节点总是内联的)

注意代码片段的结果。color是红色,margin-left是零,尽管父级具有左边距,并且width(以及height)是auto

var source = document.querySelector('.bar');
var sourceStyle = window.getComputedStyle(source);
var sourceTag = source.tagName;
var clone = document.createElement(sourceTag);
var child = document.createElement('foo');
var head = document.querySelector('head');
child.innerHTML = 1;
child.setAttribute('style', 'display: inline;');
clone.appendChild(child);
clone.setAttribute('style', sourceStyle.cssText);
head.appendChild(clone);
alert(window.getComputedStyle(source).marginLeft); // 100px
alert(window.getComputedStyle(child).color); // rgb(255, 0, 0);
alert(window.getComputedStyle(child).marginLeft); // 0px
alert(window.getComputedStyle(child).width); // auto
.bar {
  color: red;
  margin-left: 100px
  }
<html>
  <head>
    <title>An example</title>
  </head>
  <body>
    <div class="bar">
      foo
    </div>
  </body>
</html>

你的问题的答案是,你不能。样式应用于图元,并根据其内容进行造型。元素的文本内容不直接设置样式,因为它只是数据。其他答案和评论只是获得元素样式的建议,而这不是你所要求的。因此,您所要求的无法实现,因为没有对元素的数据(文本节点)应用样式。