我知道我一定在这里遗漏了一些东西,但我似乎无法让它发挥作用。
我已经使用文档头部部分内的样式标签为 html 文档的主体分配了背景颜色,但是当我尝试通过 JavaScript 读取它时,我什么也得不到:
<html>
<head>
<style>
body { background-color: #ff0; }
</style>
</head>
<body>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
.. 但是,如果我指定内联样式,它会起作用:
<html>
<head></head>
<body style='background-color: #ff0;'>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
我知道我遗漏了一些基本的东西,但我今天心不在焉——谁能告诉我为什么我的第一个场景不起作用?
谢谢
最佳答案
DOM 元素的 style
属性仅指元素的内联 样式。
根据浏览器,您可以使用 DOM CSS 获取元素的实际样式
以火狐为例:
var body = document.getElementsByTagName("body")[0];
var bg = window.getComputedStyle(body, null).backgroundColor;
或者在 IE 中:
var body = document.getElementsByTagName("body")[0];
var bg = body.currentStyle.backgroundColor;
关于javascript - 从 Javascript 读取非内联 CSS 样式信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098349/