Javascript get CSS style for ID

て烟熏妆下的殇ゞ 提交于 2019-12-23 03:31:22

问题


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>

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

回答1:


Create a new element with given ID and append it to the document. Then just read the value and remove the element.

Example:

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



回答2:


I don't think the answer was a very good one as it requires adding elements to the DOM which may disrupt what you are trying to do or create visual glitches.

Using document.styleSheets I think you can get a less invasive solution. (see here)

try something like:

var result;
var SS = document.styleSheets;
for(var i=0; i<SS.length; i++) {
    for(var j=0; j<SS[i].cssRules.length; j++) {
        if(SS[i].cssRules[j].selectorText == "#custom") {
            result = SS[i].cssRules[j].style;
        }
    }
}

This should give you an object which will contain all of the styles as the keys. keep in mind you may need a little more complex algorithm if the style is redeclared within the stylesheets.



来源:https://stackoverflow.com/questions/9311172/javascript-get-css-style-for-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!