有以下代码
<head>
<style>
body { background-color:green; }
</style>
</head>
<body>
<script>
alert(document.getElementsByTagName("BODY")[0].style.backgroundColor);
</script>
</body>
警报未显示任何内容(无结果,空字符串)。
当我将样式定义移动到 body
时标签( <body style="background-color:green">
)它按预期工作 - 返回“绿色”字符串。为什么获取内部样式(style
标签内)值不起作用?
最佳答案
元素的 .style
属性显示由 style
属性设置的样式或直接分配给元素属性的样式,但不显示计算的样式 ( HTMLElement.style )。为此,您必须使用 Window.getComputedStyle()
var style = window.getComputedStyle(document.getElementsByTagName("BODY")[0]);
alert(style.backgroundColor)
关于html - 内部CSS样式定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775673/