Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


main.css
-------
#myLayer {
  position: absolute;
  width: 200px;
  height: 100px;
  color: #0000ff;
}

main.js
-------
var ob = document.getElementById("myLayer");
var pos = ob.(getPosition);
// Pos should equal "absolute" but
// ob.style.position would equal null
// any way to get absolute?


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...