最近正在写名为JCL的javascript框架
但是中途遇到了问题就是获取style值得时候不够智能
所以在网上找了一翻,终于找到了解决方法。
传统方式
<div id='div' style='width:20px;'></div>
<script type='text/javascript'>
alert(document.getElementById('div').style.width); //return 20px
alert(document.getElementById('div').style.height); //return 空
</script>
但这种方法仅限于标签中有style的情况下可以获取
改良方法
runtimeStyle 运行时的样式!可覆盖style的属性!
currentStyle 指 style 和 runtimeStyle 的结合!
runtimeStyle 运行时的样式!可覆盖style的属性!
currentStyle 指 style 和 runtimeStyle 的结合!
<style>#div{width:20px;}</style>
<div id='div'></div>
<script type='text/javascript'>
//if IE
alert(document.getElementById('div').currentStyle.width); //return 20px
alert(document.getElementById('div').currentStyle.height); //return auto
//if Mozilla
alert(getComputedStyle(document.getElementById('div'), '').width); //return 20px
alert(getComputedStyle(document.getElementById('div'), '').height); //return 0px
</script>
这个方法相当好,可以返回外部style文件里的属性。但是有个缺点,就是不能正确返回没有定义的属性值。
最终方法
//offsetHeight & offsetWidth
//if NO DocType & IE
//var other = borderTop + borderBottom + paddingTop + paddingBottom;
//offsetHeight = height>other? height: other;
//if HTML & XHTML DocType & IE & Mozilla
//offsetHeight = height + paddingTop + paddingBottom + borderTop + borderBottom;
//如:alert(document.getElementById('div').offsetHeight + 'px')
这样可以很好的获得宽度和高度了
备注:本人建议获取的时候用offsetHeight,offsetWidth¤tStyle&getComputedStyle
但是设置的时候最好使用element.style.width = '20px'这样的形式
提供帮助
(网页来源:http://hi.baidu.com/my_labs/blog/item/b5fd592d09926ce48a1399e1.html)

