javascript获取css属性值方法:getcomputedstyle和currentstyle
1 .对于元素的内联css样式(
hello
),可以直接使用element.style.color来直接获取css属性的值;
2. 但是对于外部定义的css样式使用这种方式就无法获取了,而且ie浏览器和其他标准浏览器(firefox,chrome,opera,safari)使用的方法不一样,ie浏览器使用element.currentstyle,w3c标准浏览器使用getcomputedstyle来获取。
1. ie获取元素外部定义的css属性值: element.currentstyle
currentstyle对象返回了元素上的样式表,但是style对象只返回通过style标签属性应用到元素的内嵌样式。
因此,通过currentstyle对象获取的样式值可能与通过style对象获取的样式值不同。
例如,如果段落的color属性值通过链接或嵌入样式表设置为红色( red ),而不是内嵌的话,对象.currentstyle.color 将返回正确的颜色,而对象style.color不能返回值。但是,如果用户指定了 ,currentstyle和style对象都将返回值 red。
currentstyle对象反映了样式表中的样式优先顺序。在 html 中此顺序为:
1) 内嵌样式
2) 样式表规则
3) html 标签属性
4) html 标签的内部定义
2. w3c获取元素外部定义的css属性值: window.getcomputedstyle(element, pseudoelt)
element必选,html元素
pseudoelt必选,获取该元素的伪类样式
复制代码 代码如下:
function getstyle(node, property){
if (node.style[property]) {
return node.style[property];
}
else if (node.currentstyle) {
return node.currentstyle[property];
}
else if (document.defaultview && document.defaultview.getcomputedstyle) {
var style = document.defaultview.getcomputedstyle(node, null);
return style.getpropertyvalue(property);
}
return null;
}