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

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

Read CSS property of an element using JavaScript

So if there is a css file linked to a webpage like:

<link href="style.css" rel="stylesheet" type="text/css">

and i want to read a certain property, e.g a div has className='layout' and i want to read the details of this property using JavaScript, how can i do that?

I have searched a lot but almost have no luck, please suggest.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You have got two options:

  1. Manually enumerating and parsing the document.styleSheets object (not recommended, unless you want to get all specific style properties defined by a certain selector).
  2. Create an element matching the selector, and use the getComputedStyle or currentStyle (IE) method to get the property value.

In your example, attempt to get a certain property (let's say: color) of a div with class="layout":

function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}
window.onload = function(){
    var d = document.createElement("div"); //Create div
    d.className = "layout";                //Set class = "layout"
    alert(getStyleProp(d, "color"));       //Get property value
}

Regarding comment at your question, another function:
The function below will ignore inline style definitions of the current element. If you want to know the style definitions inherited from a stylesheet (without inherited style definitions of the parent elements), traverse the tree, and temporary wipe the .cssText property, as shown in the funcion below:

function getNonInlineStyle(elem, prop){
    var style = elem.cssText; //Cache the inline style
    elem.cssText = "";        //Remove all inline styles
    var inheritedPropValue = getStyle(elem, prop); //Get inherited value
    elem.cssText = style;     //Add the inline style back
    return inheritedPropValue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...