currentStyle、getComputedStyle

来源:互联网 发布:youtube未连接到网络 编辑:程序博客网 时间:2024/04/28 05:54
周末写了个原生的animation组件,其中使用原生的document.getElementById('...').style来获取元素的相关样式值,但是奇怪的是获取不到相应的值:
body{margin:0 auto;text-align:center;}div{position:relative;left:10px;}var dom1 = document.getElementById('pic1');console.log(dom1.style.left);

控制台中显示为空。 


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


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


获取后返回10px。


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