js 獲取DOM元素樣式

2021-08-20 02:32:50 字數 2101 閱讀 9071

html的樣式寫入方法有:1、行內樣式;2、內嵌樣式;3、外聯樣式表。

行內樣式:一般是用style寫在dom元素上的,例如:

;內嵌樣式:一般是用style寫在head標籤內的。;

外聯樣式:一般是用link標籤或者是import引入的。但import引入的時候一定要放在style標籤內。

獲採樣式:

一、ele.style

通過這種方式只能獲取到寫在行內的樣式。其他兩種是獲取不到的。例如:

var con = document.getelementbyid("con");    con.style.height;    //只能獲取到寫在行內的height值。

二、ele.getcomputedstyle  (唯讀)

可以獲取到當前元素所使用到額最終的css屬性值,返回是乙個css樣式宣告物件。

用法:var style = window.getcomputedstyle(dom,[pseudoelt]);

dom 用於獲取計算樣式的element   pseudoelt   指定乙個要匹配的偽元素的字串。必須對普通元素省略(或null)

例如:

得到的結果如下:
如果想獲取到其中的高度值(height)則可以:var h = window.getcomputedstyle(a).height;   這樣就可以拿到高度值。
三、ele.currentstyle

在舊版本的ie瀏覽器想要達到和getcomputedstyle的功能。可以使用currentstyle方法

例如:var test = document.getelmentbyid('test');

console.log(test.currentstyle.color)    //可以拿到id為test的元素的字型顏色

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

用法:
window.getcomputedstyle(element,null).getpropertyvalue(屬性);
例如:var test = document.getelmentbyid('test');
window.getcomputedstyle(test, 

null

).getpropertyvalue(

"background-color"

);

注意:屬性名不支援駝峰格式,ie6-8不支援該方法,需要使用下面的方法
五、getattribute與getpropertyvalue類似,有一點的差異是屬性名駝峰格式

例子:

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

window.getcomputedstyle(test, null).getpropertyvalue("backgroundcolor");注意:該方法只支援ie6-8

六、使用jquery.js來獲採樣式其實jq獲取元素的樣式也是對

ele.currentstyle和

ele.

getcomputedstyle、getpropertyvalue、getattribute 進行了整體的封裝。

JS 獲取dom元素

box class one name bbb style width 100px height 100px background color pink div1div box1 class one div1div box2 class one div1div 通過 id來獲取元素 var box d...

js 獲取dom元素方法

js 獲取dom元素的八種方法 通過id獲取 getelementbyid 通過name屬性 getelementsbyname 通過標籤名 getelementsbytagname 通過類名 getelementsbyclassname 通過選擇器獲取乙個元素 queryselector 通過選擇...

獲取 DOM 元素設定的樣式屬性

document.getelementbyid style獲取的是元素行間設定的樣式,不能獲取到css中設定的樣式。如果要獲取css中設定的樣式,可以試試getcomputedstyle 標準瀏覽器 或者currentstyle ie低版本 let target document.getelemen...