window.getComputedStyle详解
window.getComputedStyle
说明:
getComputedStyle()返回元素的所有CSS属性的计算值
语法:
var style = window.getComputedStyle(element[, pseudoElt]);
参数说明:
element:目标元素的DOM对象
pseudoElt:指明要匹配的伪元素,对于普通元素必须指定为null(或省略)(or not specified翻译成省略不知道有没有问题,不过测试结果表明对于普通元素确实可以省略该参数)
返回值style为CSSStyleDeclaration对象.
注意:Gecko2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)之前的版本中pseudoElt参数是必需的.对于其它主流的浏览器而言,若该参数指定为null,则可以省略.Gecko后来也改成和其它浏览器保持一致.
测试:
<a href="#" id="showAndHide">show and hide</a>
<script type="text/javascript" src="./jquery-1.8b1.js"></script>
<script>
$('#showAndHide').click(function() {
var dom = this;
console.log(getComputedStyle( dom ));
});
</script>
例1:
var elem1 = document.getElementById("elemId");
var style = window.getComputedStyle(elem1, null);
// this is equivalent:
// var style = document.defaultView.getComputedStyle(elem1, null);
例2:
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
官方文档里有一段关于getComputedStyle()与元素的style属性的区别
Description
The returned object is of the same type that the object returned from the element's style property, however the two objects have different purpose. The object returned from getComputedStyle is read-only and can be used to inspect the element's style (including those set by a <style> element or an external stylesheet). The elt.style object should be used to set styles on a specific element.
这段话只是说明getComputedStyle获取的值是只读的并且可被用于检测元素的样式(包括style属性和外部样式).而elt.style可被用于设置指定元素的样式.
以chrome为例查看getComputedStyle()与元素的style属性的区别,请注意其中cssText属性的区别
<a href="#" id="showAndHide">show and hide</a>
<script type="text/javascript" src="./jquery-1.8b1.js"></script>
<script>
$('#showAndHide').click(function() {
var dom = this;
console.log(getComputedStyle( dom ));
console.log( dom.style );
});
</script>
defaultView
在很多在线的domo中,getComputedStyle总是被当作document.defaultView的方法使用,其实这不是必需的. 因为getComputedStyle是存在于window对象. 使用Firefox 3.6访问框架样式是唯一一处必须使用defaultView的地方.
获取伪元素(如:after, :before, :marker, :line-marker)的样式
直接给出官方的Demo:
<style>
h3:after {
content: ' rocks!';
}
</style>
<h3>generated content</h3>
<script>
var h3 = document.querySelector('h3'),
result = getComputedStyle(h3, ':after').content;
console.log('the generated content is: ', result); // returns ' rocks!'
</script>