js中style,currentStyle和getComputedStyle的区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js中style,currentStyle和getComputedStyle的区别相关的知识,希望对你有一定的参考价值。

js中style,currentStyle和getComputedStyle的区别 MarysMa 在js中用xx.style.marginTop是无法获取写在css或<sytle>标签中的margin-top之类的样式值(包括width,height等)。

这就是style属性的限制:

style

只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。(内联样式: body中标签里用style直接写的样式。)

currentStyle

可以弥补style的不足,但是只适用于IE。

getComputedStyle

同currentStyle作用相同,但是适用于FF、opera、safari、chrome。

所以兼容的取值写法:
getElementStyle: function(el,attr){
//获取el当前的attr样式,解决ie问题
return el.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
 

注意:

currentStyle和getComputedStyle只能用于获取页面元素的样式,不能用来设置相关值。

如果要设置相应值,应使用style。

 
科普:
 
getComputedStyle:是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读。(总而言之就是获取一堆样式。。。)语法如下:
var style = window.getComputedStyle("元素", "伪类");
 
 
顺带一提jq库的$.css()就是用getComputedStyle和getPropertyValue两者结合。
 
详细可以看文章:

获取元素CSS值之getComputedStyle方法熟悉 ? 张鑫旭

以上是关于js中style,currentStyle和getComputedStyle的区别的主要内容,如果未能解决你的问题,请参考以下文章

js中getComputedStyle()与currentStyle()style()方法的区别

js中getComputedStyle()与currentStyle()style()方法的区别

js中style,currentStyle和getComputedStyle的区别以及获取css操作方法

style和getComputedStyle(ff)和currentStyle

js中获取css样式属性值

JavaScript中style, currentStyle和 getComputedStyle的异同