2012-02-16 32 views
1

我希望能够从未在网页上使用的CSS元素获取样式。例如,这是页面:Javascript获取CSS样式为ID

<html> 
<head> 
<style type="text/css"> 
#custom{ 
background-color: #000; 
} 
</style> 
</head> 

<body> 
<p>Hello world</p> 
</body> 
</html> 

正如您所看到的ID'custom'有一个值,但未在文档中使用。我想在页面中使用“自定义”的所有值。我来最接近的是:

el = document.getElementById('custom'); 
var result; 
var styleProp = 'background-color'; 
if(el.currentStyle){ 
    result = el.currentStyle[styleProp]; 
    }else if (window.getComputedStyle){ 
    result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp); 
    }else{ 
    result = "unknown"; 
} 
+1

有没有你想重新实现CSS类特殊的原因?请告诉我们你最终的结果是什么,我们可以帮助你达到目标。 – 2012-02-16 12:26:40

回答

5

创建元素,并将其添加到文档中,暂时:

var result, 
    el = document.body.appendChild(document.createElement("div")), 
    styleProp = 'background-color', 
    style; 

el.id = 'custom'; 
style = el.currentStyle || window.getComputedStyle(el, null); 
result = el[styleProp] || "unknown"; 

// Remove the element 
document.body.removeChild(el);