<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>getStyle</title>
<style>
.defaultCls{
width:200px;
height:300px;
border:1px solid windowtext;
}
</style>
<script>
function check(){
var obj = document.getElementById("content");
alert(getStyle(obj,"width"));
}
function getStyle(obj,styleName){
if (styleName==null){
return "";
}
var str = styleName;
var pos = str.indexOf("-");
while(pos>=0){
if (pos == str.length - 1){
str = str.substring(0,pos);
}
else if(pos == str.length - 2){
str = str.substring(0,pos)+str.substring(pos + 1).toUpperCase();
}
else{
str = str.substring(0,pos)+str.substring(pos + 1,pos + 2).toUpperCase()+str.substring(pos + 2);
}
pos = str.indexOf("-");
}
var style = "";
if (obj.currentStyle)
style = obj.currentStyle[str];
else if (window.getComputedStyle)
style = document.defaultView.getComputedStyle(obj,null).getPropertyValue(str);
return style || "";
}
</script>
</head>
<body>
<div id="content" style="font-size:12px" class="defaultCls">sfsd
</div>
<input type="button" value="check" onclick="check()" />
</body>
</html>
平常我们都是使用dom.style.display这种方式去获取某一个样式,可这样就会有个问题,如果我的样式是定义在class中的,这种方式就无能为力了。
还好浏览器提供给我们解决方法,那就是使用currentStyle属性或者是document.defaultView.getComputedStyle函数,不同浏览器的处理方式不一样。
这样我们就可以获取到我们想要的结果,不论是定义在style中还是class中。
上面的代码在ie以及Firefox中测试通过,其他浏览器未测试。