sbi*_*nko 24 html javascript css
window.getComputedStyle()方法仅接受元素节点.有没有办法可靠地获得确定文本节点的可视化表示的样式?
我意识到节点不能具有style
属性,但它们肯定是样式化的,因为它们继承了父元素的样式.或许有一种方法可以从父元素中获取与文本节点的可视化表示相关的所有计算样式吗?
请注意,将节点包装在a中span
是不可能的:这会影响CSS规则,例如span:nth-child
或span + span
等.
如果文本节点是元素中的唯一节点,则可以简单地使用getComputedStyle()
它parentNode
.
但是,请考虑以下事项:
div {border: 1px solid black;}
Run Code Online (Sandbox Code Playgroud)
<div>This <em>is</em> a <strong>test</strong></div>
Run Code Online (Sandbox Code Playgroud)
你不能说"这个"和"一个"都有边框.说"This"有左上角的边框,而"a"只有上下边框会不准确?这是值得怀疑的.
如果你限制自己的专门适用于文本样式(颜色,背景,textDecoration,字体等),应用getComputedStyle()
上parentNode
应始终工作.
我会自己尝试一下.
window.getComputedStyle()
在父元素上使用并存储标记名称和样式信息.style
属性为其指定样式.<foo>
元素(严格来说,它应该是当前CSS规则中未提及的标记名称,因此它们不会影响它).<head>
文档的(Webkit特定的).window.getComputedStyle()
的子元素.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
Run Code Online (Sandbox Code Playgroud)
.bar {
color: red;
margin-left: 100px
}
Run Code Online (Sandbox Code Playgroud)
<html>
<head>
<title>An example</title>
</head>
<body>
<div class="bar">
foo
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)