内部CSS样式定义

问题描述:

有下面的代码内部CSS样式定义

<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) 
+0

因此,在_style_标签内部定义的样式被称为“计算”并拥有它自己的getComputedStyle方法吗? – Mulligun81

+0

@RobertWade'style.background-color'将会是一个语法错误,因为可以通过移除每个'-'并将'-'后面的字符改为大写来完成访问。 –

+0

@ Mulligun81不,'

正如已经t.niese回答,getComputedStyle()是JavaScript方法应当用于获取CSS样式。

它实际上做了什么?

那么,它会在浏览器窗口中呈现后抓取样式值,并且您看不到由document.body.style.backgroundColor返回的空白。

我们可以使它更健壮,更适合浏览器; currentStyle方法适用于较旧版本的IE和Opera。

<html> 
 

 
<head> 
 
    <style> 
 
    body { 
 
     background-color: green; 
 
    } 
 
    </style> 
 
</head> 
 

 
<body> 
 
    <script> 
 
    // getComputedStyle for modern browsers, currentStyle for IE 
 
    var style = window.getComputedStyle ? getComputedStyle(document.body) : document.body.currentStyle; 
 
    alert(style.backgroundColor); 
 
    </script> 
 
</body> 
 

 
</html>

请注意,这里的方法返回的颜色值将在RGB。