計算後的樣式

2022-03-26 16:10:41 字數 1699 閱讀 9201

一、高階瀏覽器和低階瀏覽器的不同寫法

w3c制定的標準

api,所有

現代瀏覽器(包括ie9,但不包括之前的版本)都實現了

window.getcomputedstyle()

,該方法接收乙個要進行樣式計算的元素,並返回乙個

樣式物件

。樣式物件

提供了getpropertyvalue()的方法,用於檢索特定css樣式屬性的計算樣式。getpropertyvalue方法接收

css屬性名稱,而不是駝峰式的名稱。

getpropertyvalue()

可以不寫,直接用方括號來檢索屬性也可以

console.log(getcomputedstyle(obox)["background-color"]); //顏色計算後結果就得到rgb的值

console.log(getcomputedstyle(obox)["background-position"]);

console.log(getcomputedstyle(obox)["background-image"]);

console.log(getcomputedstyle(obox)["border-color"]);

dom提供給js的

api非常牛,乙個元素此時的狀態,完全可以被得到,好用的屬性,但是不相容。所以

ie678

不相容getcomputedstyle()方法,寫另外一套寫法:附加在元素身上的

currentstyle

屬性,它表示和

style

點語法意義,使用駝峰命名法。

總結:

高階瀏覽器:

window.getcomputedstyle(obox).getpropertyvalue("padding-left");

getcomputedstyle(obox).getpropertyvalue("padding-left");

getcomputedstyle(obox)["padding-left"];

ie6/7/8

obox.currentstyle.paddingleft

obox.currentstyle["paddingleft"];

封裝相容寫法:

ie678瀏覽器,不認識

getcomputedstyle

視為錯誤

chrome等瀏覽器,不認識

currentstyle

視為錯誤

只瀏覽器的能力。所以要進行能力檢測,可以在不同瀏覽器中得到相容性的寫法,輸出css屬性的值。

封裝乙個相容性的函式獲取乙個元素某個css屬性值的方法。

api:傳入兩個引數,第乙個是元素物件,第二個是

css屬性名

返回值是這個傳入元素物件的屬性值。

var obox = document.getelementbyid('box');

function getstyle(obj,property));

return window.getcomputedstyle(obj)[property];

}else);

return obj.currentstyle[property];

}}alert(getstyle(obox,"paddingleft"));

計算後樣式

1,高階瀏覽器和低階瀏覽器的不同寫法。現在我們只能得到行內的樣式,事實上dom提供了可靠的api,得到計算後的樣式。w3c制定的標準api所有現代瀏覽器 包括ie9,但不包括之前的版本 都實現了window.getcomputedstyle 該方法接受乙個要進行樣式計算的元素,並返回乙個樣式物件。樣...

獲取CSS計算後的樣式

window.onload function else console.log width var width window.getcomputedstyle div width var width div.currentstyle.width json遍歷 var opation for var ...

獲取計算後樣式的方法(相容版)

標準下獲取計算後樣式getcomputedstyle el attr ie下獲取計算後樣式el.currentstyle attr 相容版封裝函式 function getstyle el,attr return getcomputedstyle el attr 注 el 元素 attr 屬性名稱 ...