没有jQuery告诉外部css文件或内部样式表的信息

时间:2014-10-18 22:09:47

标签: javascript jquery html css

我想使用javascript 而不使用jQuery或任何其他JS库来返回内部/外部样式的样式

<style type="text/css"> <!-- From internal/external stylesheet -->
    div{
        height:30px;
        width:45px;
        background-color:#4445C7;
    }
</style>
<div id="counter-element" style="width:3px;height:10px;"></div>
<div id="example"></div>
<script type="text/javascript">
    function getStyle(elem,prop){
        return elem.style[prop];
    }
    alert(getStyle(document.getElementById("counter-element"),"origional-background-color"); //I know this won't work. I'm just putting it in for an example
    alert(getStyle(document.getElementById("example"),"background-color");
</script>

1 个答案:

答案 0 :(得分:0)

var es=getStyle(document.getElementById("someId"),"background-color");

一样使用它

&#13;
&#13;
function getStyle(Elm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(Elm, "").getPropertyValue(strCssRule);
    }
    else if(Elm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = Elm.currentStyle[strCssRule];
    }
    return strValue;
}
&#13;
&#13;
&#13;