如果没有jQuery,则会从外部css文件或内部样式表中告知信息

Without jQuery tell information from external css file or internal stylesheet

本文关键字:内部样式表 信息 文件 css jQuery 从外部 如果没有      更新时间:2023-09-26

我想在没有jQuery或任何其他JS库的情况下使用javascript从内部/外部样式表返回样式

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

像这样使用var es=getStyle(document.getElementById("someId"),"background-color");

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