分两种情况讨论:
1、使用内联样式,即直接把CSS写在HTML元素的style属性中
通过以下js代码可以获取width等属性,
在firefox,ie,opera,safari,chrome上都可以取得到宽度和高度值。
2、使用嵌入、链入或引入样式表(非内联样式),这时候通过element.style.width是获取不到的
--></mce:style><style type="text/css" mce_bogus="1"> #d2 {
width:400px;
height:200px;
border:5px solid gray;
padding:5px;
}
</style>
<mce:script type="text/javascript"><!--
window.onload=function(){
//2、使用嵌入、链入或引入样式表(非内联样式)
//ie:通过currentStyle
alert(document.getElementById('d2').currentStyle.width);//400px ie
//ff,safari,opera,chrome:通过window.getComputedStyle
var el=document.getElementById('d2');
alert(window.getComputedStyle(el,null).style.width);//400px safari,opera,chrome
}
// --></mce:script>
</head>
<body>
<div id="d2"></div>
</body>
</html>
最后封装到一个方法中,
'currentStyle' in el ? sty=el.currentStyle : 'getComputedStyle' in window
? sty=window.getComputedStyle(el,null) : null;
if(cssName==="opacity" && document.all){
f = el.filters;
f && f.length>0 && f.alpha ? fv=f.alpha.opacity/100 : fv=1;
return fv;
}
cssName==="float" ? document.all ? cssName='styleFloat' : cssName='cssFloat' : cssName;
sty = (len==2) ? sty[cssName] : sty;
return sty;
}
如果只想获取元素的style对象,则只传第一个参数,第二个参数是获取该对象style属性为styName的值。