訪問元素的樣式
一、style
任何支持style特性的HTML元素在Javascript中都有一個對應的style屬性。這個style對象是CSSStyleDeclaratioin的實例。包含著通過HTML的style特性指定的所有樣式信息,不包含外部樣式表和內嵌入樣式表經層疊而來的樣式。
在style特性中指定的任何CSS屬性都將表現為這個style對象的相應屬性。
對于使用短劃線的CSS屬性,要轉換成駝峰大小寫形式
css : background-color
javascript:e.style.backgroundColor
通過(style.屬性名)取得的屬性,可讀可寫!
let e = document.getElementsByClassName('demo')[0];
e.style.backgroundColor = 'yellow';
二、DOM樣式屬性和方法 (e.style的屬性和方法)
<div class="demo" style="background-color:red"></div>
-------
let e = document.getElementByClassName('demo')[0];
1) cssText
e.style.cssText 能返回style特性中的CSS代碼
e.style.cssText // "background-color:red"
2) length
e.style.length 返回應用給元素的css屬性的數量
e.style.length // 1
3) item(index)
e.style.item 返回給定位置的css屬性的名稱。配合 length屬性可以遍歷style對象
4) getPropertyValue(propertyName)
返回給定的屬性的字符串值
e.style.getPropertyValue('background-color') // red
5) setPropertyValue(propertyName,value,priority)
將給定屬性設置為相應的值,并加上優先權標志(‘important’ | '')
e.style.setPropertyValue('border','1px solid black');
<div class="demo" style="background-color:red; border: 1px solid black"></div>
getComputedStyle()
document.defaultView.getComputedStyle() | window.getComputedStyle();
style對象只能提供支持style特性的任何元素的樣式信息,對于外部和內嵌的或繼承而來的元素的樣式信息不支持。
document.getComputedStyle() 確能獲取當前元素的所有最終使用的CSS屬性值
getComputedStyle()有兩個參數
①要取得計算樣式的元素
②一個偽元素字符串(如':after')如果不需要,可以是null;
document.defaultView.getComputedStyle();
//當只寫一個參數的話,就獲取這個元素的樣式信息。
//如果有二參數的話,就是獲取這個元素的偽元素的樣式信息。
這個方法是只讀的!!!只讀的!
IE的方法是e.currentStyle!