getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读。
语法如下:
var style = window.getComputedStyle("元素", "伪类"); 例如: var dom = document.getElementById("test"), style = window.getComputedStyle(dom , ":after");
我们可以用来获取伪类的样式,这是jquery.css()无法做到的!
getComputedStyle与style的区别
1.getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写
2.getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象.而element.style只能获取元素style属性中的CSS样式
getComputedStyle与currentStyle的区别
currentStyle是IE浏览器特有一个属性,element.currentStyle返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的style属性等)。
获取一个元素高度的兼容写法:
var dom = document.querySelector(".testDiv"); var oStyle = dom.currentStyle ? dom.currentStyle : window.getComputedStyle(dom, null); alert(oStyle.height);
getPropertyValue
getPropertyValue方法可以获取CSS样式申明对象上的属性值(直接属性名称),例如:
window.getComputedStyle(element, null).getPropertyValue("float");
getPropertyValue方法IE9+以及其他现代浏览器都支持,对于IE8,我们需要使用getAttribute, 或直接写css样式名称获取。
示例:
var dom = document.querySelector(".testDiv"); var oStyle = dom.currentStyle ? dom.currentStyle : window.getComputedStyle(dom, null); if (oStyle.getPropertyValue) { alert(oStyle.getPropertyValue("float")); } else { //IE8 //alert(oStyle.getAttribute("float"))//null //alert(oStyle.styleFloat); alert(oStyle.getAttribute("styleFloat")); }