使用JavaScript读取元素的CSS属性 [英] Read CSS property of an element using JavaScript
问题描述
因此,如果有一个css文件链接到一个网页,如:
So if there is a css file linked to a webpage like:
<link href="style.css" rel="stylesheet" type="text/css">
并且我想读取某个属性,例如div有className ='layout'使用JavaScript阅读此属性的详细信息,我该如何做?
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?
我搜索了很多,但几乎没有运气,请建议。 b $ b
I have searched a lot but almost have no luck, please suggest.
推荐答案
您有两个选项:
- 手动枚举并解析
document.styleSheets
对象(非推荐,除非你想获得由某个选择器定义的所有特定样式属性)。 - 创建一个与选择器匹配的元素,并使用
getComputedStyle
或currentStyle
(IE)方法获取属性值。
- Manually enumerating and parsing the
document.styleSheets
object (not recommended, unless you want to get all specific style properties defined by a certain selector). - Create an element matching the selector, and use the
getComputedStyle
orcurrentStyle
(IE) method to get the property value.
在您的示例中,尝试获取一个div的特定属性(比方说: color
) class =layout
:
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
}
>,另一个函数:
下面的函数将忽略当前元素的内联样式定义。如果你想知道从样式表继承的样式定义(没有父元素的继承样式定义),遍历树,然后临时擦除 .cssText
属性,如图所示在函数中:
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;
}
这篇关于使用JavaScript读取元素的CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!