js中style,currentStyle和ge…

来源:互联网 发布:小米手机淘宝商城 编辑:程序博客网 时间:2024/05/16 16:09
原文地址:js中style,currentStyle和getComputedStyle的区别作者:herry
周末写了个原生的animation组件,其中使用原生的document.getElementByIdx_x_x('...').style来获取元素的相关样式值,但是奇怪的是获取不到相应的值:
<style>
body{margin:0auto;text-align:center;}
div{position:relative;left:10px;}
</style>
<div id="pic1">
<imgsrc="http://pic1.xihuan.me/edr/196__/t02362982432fa1b14e.jpg">
</div>
<script>
var dom1 = document.getElementByIdx_x('pic1');
console.log(dom1.style.left);
</script>
控制台中显示为空。 

查询了相关资料发现问题如下:
style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。
currentStyle可以弥补style的不足,但是只适用于IE
getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome

写了个getStyle的自定义函数,来兼容ie和其他浏览器,使用getStyle来获取页面中元素的样式,问题解决。
getElementStyle: function(el,attr){
//获取el当前的attr样式,解决ie问题
returnel.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
获取后返回10px。

注意:
currentStyle和getComputedStyle只能用于获取页面元素的样式,不能用来设置相关值。
如果要设置相应值,应使用style
原创粉丝点击