window.getComputedStyle可獲取 偽類元素 樣式
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>
window.getComputedStyle可獲取 偽類元素 樣式