从Javascript中读取非内联CSS样式信息 [英] Reading non-inline CSS style info from Javascript
问题描述
我知道我必须在这里缺少一些东西,但是我似乎不能让这个工作。
I know I must be missing something here, but I cannot seem to get this to work.
我为html文档的主体分配了一个背景颜色使用文档头部内的样式标签,但是当我尝试通过JavaScript读取它时,我什么都不会:
I have assigned a background color to the body of an html document using the style tags inside the head section of the document, but when I try to read it via JavaScript, I get nothing:
<html>
<head>
<style>
body { background-color: #ff0; }
</style>
</head>
<body>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
..但是,如果我指定样式内联,它的工作原理:
.. however, if I assign the style inline, it works:
<html>
<head></head>
<body style='background-color: #ff0;'>
<a href="#" onclick='alert(document.body.style.backgroundColor)'>Click Here</a>
</body>
</html>
我知道我缺少一些基本的东西,但我的心不在今天的区域 - 告诉我为什么我的第一个方案不工作?
I know I am missing something basic, but my mind is not in the zone today -- can anyone tell me why my first scenario is not working?
感谢
推荐答案
DOM元素的 style
属性仅指元素的内联样式。
The style
property of a DOM element refers only to the element's inline styles.
根据浏览器的不同,您可以使用 DOM CSS 获取元素的实际样式
Depending on the browser, you can get the actual style of an element using DOM CSS
在firefox中,例如:
In firefox, for example:
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中读取非内联CSS样式信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!