获取元素的某个CSS值的兼容性方法。

时间:2022-08-26 20:34:42

今天看到一个获取DOM元素CSS最终样式值的方法,整理如下。

  获取特定CSS的最终样式值的方法同样分两种情况,兼容w3c的跟IE的。

  W3C:

  使用方法,document.defaultView.getComputedStyle(el, null);这个方法会返回一个对象,叫做CSSStyleDeclaration object对象的属性即DOM对象el的各个CSS样式名称,属性的值即对应的CSS值。document.defaultView.getComputedStyle(el, null).width;即可获得el的width;

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>by 指颜</title>
<style>
#test
{width:100px;height:100px;background-color:red;}
</style>
</head>
<body>
<div id="test">
</div>
<script>
var el = document.getElementById("test");
var result = document.defaultView.getComputedStyle(el,null).width;
alert(result);
</script>
</body>
</html>

这个方法返回的对象还有一个方法:getPropertyValue(style);通过这个方法也可以获取CSS的值。两种获取CSS属性值得区别在于,直接通过属性的方法CSS的属性必须是这个格式“backgroundColor”,getPropertyValue(style)方法的属性值style为“background-color”格式。

IE:

IE通过el.currentStyle[style]的方式获取CSS属性值,CSS的属性必须是这种格式“backgroundColor”。

结合两种方法可以写出一个兼容性方法来:

function getStyle(el,style){
style = style.replace(/-([a-z])/g,function($0,$1){
return $1.toUpperCase();});
return document.defaultView ? document.defaultView.getComputedStyle(el,null)[style] : el.currentStyle[style];
};

其实IE9已经有了很大的改进,上面提到的两种方法IE9都可实现。