Javascript获取ID的CSS样式

Pau*_*aul 1 javascript css styles

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

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

<body>
<p>Hello world</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,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";
}
Run Code Online (Sandbox Code Playgroud)

And*_*y E 5

创建具有给定ID的新元素并将其附加到文档.然后只需读取值并删除元素.

例:

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

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

// Remove the element
document.body.removeChild(el);
Run Code Online (Sandbox Code Playgroud)