核心提示:Dom中getComputedStyle方法可用来获取元素中所有可用的css属性列表,以数组形式返回,并且是readonly的。IE中则用currentStyle代替。语法:arr_style=win...
Dom中getComputedStyle方法可用来获取元素中所有可用的css属性列表,以数组形式返回,并且是readonly的。IE中则用currentStyle代替。
语法:arr_style=window.getComputedStyle(elem_id,ov)
其中ov:伪元素,是否要获取伪元素属性值。如hover,active,link等属性。如果不想获取这些伪元素的属性值请填写为null。
一个HTMLElement的style属性是一个可读可写的CSS2Properties对象,就好像CSSRule对象的style属性一样。不过,Window.getComputedStyle() 的返回值是一个CSS2Properties对象,其属性是只读的。
什么是CSS2Properties 对象?
当要读取具体某个css属性时必须使用getPropertyValue或getPropertyCSSValue。
至于getPropertyValue和getPropertyCSSValue有什么区别,getPropertyValue返回的是一个string,而getPropertyCSSValue返回的是一个CSS2Properties对象。
例如,下面两个getStyle的输出结果是一样的。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>测试getPropertyCSSValue</title> <style type="text/css"> #elem { position:absolute; top:200px; left:100px; height:100px; } </style> <script type="text/javascript"> window.onload = function(){ getStyle(); } /*function getStyle(){ var container = document.getElementById("elem"); var str = window.getComputedStyle(container,null).getPropertyValue("height"); document.getElementById("output").innerHTML = str; }*/ /*function getStyle(){ var container = document.getElementById("elem"); var str = window.getComputedStyle(container,null).getPropertyCSSValue("top").cssText; document.getElementById("output").innerHTML = str; }*/ </script> </head> <body> <p id="elem">dummy</p> <p id="output"></p> </body> </html>