因此,如果有一个 css 文件链接到如下网页:
<link href="style.css" rel="stylesheet" type="text/css">
我想读取某个属性,例如 div 有 className='layout' 并且我想使用 JavaScript 读取此属性的详细信息,我该怎么做?
我已经搜索了很多,但几乎没有运气,请建议。
您有两个选择:
- 手动枚举和解析document.styleSheets https://developer.mozilla.org/en/DOM/document.styleSheetsobject(不推荐,除非您想获取某个选择器定义的所有特定样式属性)。
- 创建一个与选择器匹配的元素,并使用
getComputedStyle
or currentStyle
(IE) 方法来获取属性值。
在您的示例中,尝试获取某个属性(比方说:color
) 的 div 与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
}
关于您的问题的评论,另一个函数:
下面的函数将忽略当前元素的内联样式定义。如果你想知道从一个样式表继承的样式定义(没有继承父元素的样式定义),遍历树,并临时擦除.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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)