訪問元素的樣式
一、style
任何支持style特性的HTML元素在Javascript中都有一個(gè)對應(yīng)的style屬性。這個(gè)style對象是CSSStyleDeclaratioin的實(shí)例。包含著通過HTML的style特性指定的所有樣式信息,不包含外部樣式表和內(nèi)嵌入樣式表經(jīng)層疊而來的樣式。
在style特性中指定的任何CSS屬性都將表現(xiàn)為這個(gè)style對象的相應(yīng)屬性。
對于使用短劃線的CSS屬性,要轉(zhuǎn)換成駝峰大小寫形式
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 返回應(yīng)用給元素的css屬性的數(shù)量
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)
將給定屬性設(shè)置為相應(yīng)的值,并加上優(yōu)先權(quán)標(biāo)志(‘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特性的任何元素的樣式信息,對于外部和內(nèi)嵌的或繼承而來的元素的樣式信息不支持。
document.getComputedStyle() 確能獲取當(dāng)前元素的所有最終使用的CSS屬性值
getComputedStyle()有兩個(gè)參數(shù)
①要取得計(jì)算樣式的元素
②一個(gè)偽元素字符串(如':after')如果不需要,可以是null;
document.defaultView.getComputedStyle();
//當(dāng)只寫一個(gè)參數(shù)的話,就獲取這個(gè)元素的樣式信息。
//如果有二參數(shù)的話,就是獲取這個(gè)元素的偽元素的樣式信息。
這個(gè)方法是只讀的!!!只讀的!
IE的方法是e.currentStyle!