JavaScript get Styles

前端 未结 3 1954
心在旅途
心在旅途 2020-11-30 12:12

Is it possible to get ALL of the styles for an object using JavaScript? Something like:


main.css
-------
#myLayer {
  position: absolute;
  width: 200px;
          


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 12:37

    You are talking about what is known as Computed Style, check out these article on how to get it:

    • Get Styles on QuirksMode
    • Get Computed Style
    • Get the rendered style of an element

    From the last article, here is a function:

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

    How to use it:

    CSS:

    /* Element CSS*/
    div#container{
        font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
    }
    

    JS:

    var elementFontSize = getStyle(document.getElementById("container"), "font-size");
    

提交回复
热议问题