使用JavaScript读取元素的CSS属性

Joh*_*dep 6 javascript css

因此,如果有一个链接到网页的css文件,例如:

<link href="style.css" rel="stylesheet" type="text/css">
Run Code Online (Sandbox Code Playgroud)

我想读取某个属性,例如div有className ='layout',我想用JavaScript读取这个属性的详细信息,我该怎么做?

我已经搜索了很多但几乎没有运气,请建议.

Rob*_*b W 11

你有两个选择:

  1. 手动枚举和解析document.styleSheets对象(不推荐,除非您希望获取某个选择器定义的所有特定样式属性).
  2. 创建与选择器匹配的元素,并使用getComputedStyleor currentStyle(IE)方法获取属性值.

在您的示例中,尝试获取colordiv 的某个属性(比如说:) 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
}
Run Code Online (Sandbox Code Playgroud)

关于您的问题的评论,另一个功能:
下面的函数将忽略当前元素的内联样式定义.如果您想知道从样式表继承的样式定义(没有父元素的继承样式定义),则遍历树,并临时擦除.cssText属性,如下面的函数所示:

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;
}
Run Code Online (Sandbox Code Playgroud)