Javascript获取ID的CSS样式

问题描述:

我希望能够从网页上没有使用的CSS元素获取样式。例如,这是页面:

I would like to be able to get the style from a CSS element which is not used on the webpage. For example, this is the page:

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

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

,因为您可以看到IDcustom具有值,但在文档中未使用。我想获得'custom'的所有值,而不在页面中使用它。我最近的是:

as you can see the ID 'custom' has a value but is not used within the document. I would like to get all the values for 'custom' without using it in the page. The closest I have come is:

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";
}


创建元素并添加临时:

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);