獲取元素樣式

2021-09-26 20:28:58 字數 1655 閱讀 4363

1、ele.style

ele.style只能獲取寫在元素標籤中的style屬性裡的樣式值,無法獲取到定義在和通重載入進來的樣式屬性

var test = document.getelementbyid("test");

//獲取節點的color

test.style.color;

2、getcomputedstyle()

getcomputedstyle是乙個可以獲取當前元素所有最終使用的css屬性值。

window.getcomputedstyle("元素", "偽類");
接受兩個引數:要取得計算樣式的元素和乙個偽元素字串(例如「:before」) 。如果不需要偽元素資訊,第二個引數可以是null。也可以通過document.defaultview.getcomputedstyle(「元素」, 「偽類」);來使用

3、ele.currentstyle

currentstyle是ie瀏覽器自己的乙個屬性,其語法與ele.style類似,差別在於element.currentstyle返回的是元素當前應用的最終css屬性值(包括外鏈css檔案,頁面中嵌入的

var test = document.getelementbyid(「test」),

demo = test.currentstyle;

//獲取節點的color

demo.color;

注意:對於綜合屬性border等,ie返回undefined,其他瀏覽器有的返回值,有的不返回,但是borderleftwidth這樣的屬性是返回值的

4、getpropertyvalue()

getpropertyvalue獲取css樣式的直接屬性名稱

var test = document.getelementbyid('test');

window.getcomputedstyle(test, null).getpropertyvalue("background-color");

注意:屬性名不支援駝峰格式,ie6-8不支援該方法,需要使用下面的方法

5、getattribute

getattribute與getpropertyvalue類似,有一點的差異是屬性名駝峰格式

var test = document.getelementbyid('test');

window.getcomputedstyle(test, null).getpropertyvalue("backgroundcolor");

注意:該方法只支援ie6-8

jquery的css()方法,其底層運作就應用了getcomputedstyle以及getpropertyvalue方法,當我們使用原生的js開發時就可以通過以上方法獲取元素的值。

相容ie,firefox,chrome:

function getstyle(ele) else

return style;

}

獲取元素樣式

object.style attr 只可獲取html標籤內的樣式,主要用來設定css,而不可獲取style標籤中的css樣式 ie支援object.currentstyle attr ff支援getcomputedstyle object,false attr 首先是有兩個引數,元素和偽類。第二個引...

獲取元素的樣式

行間樣式 divid box1 style width 300px height 100px div console log box1 style width 非行間樣式 box2 divid box2 div console log box2 style width getcomputedstyl...

原生javascript獲取元素樣式

摘要 我們在開發過程中經常會遇到通過js獲取或者改變dom元素的樣式,方法有很多,比如 通過更改dom元素的class。現在我們討論原生js來獲取dom元素的css樣式,注意是獲取不是設定 在開始之前先說下獲取最終應用在元素上的所有css屬性物件的意思是,如果沒有給元素設定任何樣式,也會把瀏覽器預設...