因此,如果有一个链接到网页的 css 文件,例如:
<link href="style.css" rel="stylesheet" type="text/css">
我想读取某个属性,例如一个 div 有 className='layout',我想使用 JavaScript 读取这个属性的详细信息,我该怎么做?
我搜索了很多但几乎没有运气,请建议。
最佳答案
你有两个选择:
- 手动枚举和解析
document.styleSheets
对象(不推荐,除非你想获得某个选择器定义的所有特定样式属性)。 - 创建一个与选择器匹配的元素,并使用
getComputedStyle
或currentStyle
(IE) 方法获取属性值。
在您的示例中,尝试使用 class="layout"
获取 div 的特定属性(比方说:color
):
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
}
关于您的问题的评论,另一个功能:
下面的函数将忽略当前元素的内联样式定义。如果你想知道从样式表继承的样式定义(没有父元素的继承样式定义),遍历树,并临时删除 .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;
}
关于javascript - 使用 JavaScript 读取元素的 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7894577/