一、getComputedStyle
getComputedStyle 是一個可以獲取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),只讀。
語法如下:
var style = window.getComputedStyle("元素", "偽類"); //例 var dom = document.getElementById("test"); var style = window.getComputedStyle(dom , ":after"); //獲取屬性可以用 getPropertyValue (不駝峰 IE9+),getAttribute(駝峰) style.getAttribute("backgroundColor"); style.getPropertyValue("border-top-left-radius");
Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二個參數“偽類”是必需的(如果不是偽類,設置為null
);
getComputedStyle IE6~8是不支持的。
IE可以用CurrentStyle,它是IE瀏覽器自娛自樂的一個屬性
例如,我們要獲取一個元素的高度,可以類似下面的代碼:
alert((element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height);
二、style
element.style 可讀可寫。
getComputedStyle
方法獲取的是最終應用在元素上的所有CSS屬性對象(包括默認),而element.style
只能獲取元素style
屬性中的CSS樣式。
三、getBoundingClientRect()
var box=document.getElementById('box'); // 獲取元素 alert(box.getBoundingClientRect().top); // 元素上邊距離頁面上邊的距離
IE8一下只有上下左右可獲取到,默認坐標從(2,2)開始計算,
var right = box.getBoundingClientRect().right; var left = box.getBoundingClientRect().left; var width = right-left;