一、訪問元素中行內(nèi)樣式
style對象是CSSStyleDeclaration的實例,包含著通過HTML的style特性指定的所有樣式信息
但不包含與外部樣式,或嵌入式樣式層疊而來的樣式
短劃線的css屬性必須轉(zhuǎn)換成駝峰大小寫形式 (float是關(guān)鍵字,所以規(guī)定為cssFloat)
// HTML
<div style="color: blue; background-color: yellow !important;">字體</div>
// 外鏈樣式
div {
width: 100px;
height: 100px;
background-color: red;
border: 6px solid #ccc;
}
// JS
var divEle = document.querySelector('div');
1.獲取行內(nèi)樣式信息
var divStyle = divEle.style;
1.1應(yīng)用給元素的css屬性的數(shù)量
console.log(divStyle.length); // 2
1.2返回給定位置的 CSS 屬性的名稱 與length配套使用
console.log(divStyle.item(0)); // color
1.3cssText
通過它能夠訪問到 style 特性中的 CSS 代碼
在讀取模式下, cssText 返回瀏覽器對 style特性中 CSS 代碼的內(nèi)部表示
在寫入模式下,賦給 cssText 的值會重寫整個 style 特性的值
設(shè)置 cssText 是為元素應(yīng)用多項變化最快捷的方式,因為可以一次性地應(yīng)用所有變化
console.log(divStyle.cssText); // color: blue; background-color: yellow;
1.4獲取指定屬性的值
console.log(divStyle.getPropertyValue('color')); // blue
1.5如果給定的屬性使用了 !important 設(shè)置,則返回 "important" ;否則,返回空字符串
console.log(divStyle.getPropertyPriority('background-color')); // important
2.設(shè)置樣式
2.1
divStyle.color = '#FFF'; divStyle.backgroundColor = '#000';
2.2 setProperty(屬性, 屬性值, 權(quán)重)第三個參數(shù)(可選): 優(yōu)先權(quán)重 "important" 或者一個空字符串
divStyle.setProperty('color', 'green');
3.刪除屬性
removeProperty(propertyName) :從樣式中刪除給定屬性
意味著將會為該屬性應(yīng)用默認的樣式(從其他樣式表經(jīng)層疊而來)
console.log(divStyle.removeProperty('color')); // 返回給定屬性的值 green
二、計算屬性
- 雖然 style 對象能夠提供支持 style 特性的任何元素的樣式信息,但它不包含那些從其他樣式表層疊而來并影響到當(dāng)前元素的樣式信息
- “DOM2 級樣式”增強了 document.defaultView ,提供了getComputedStyle() 方法, 返回CSSStyleDeclaration 對象(與 style 屬性的類型相同),并且是計算過后的樣式(行內(nèi),內(nèi)嵌(內(nèi)部), 外鏈)
4.第一個參數(shù): 取得計算樣式的元素; 第二個參數(shù): 偽元素字符串(':after') 在舊版本之前,第二個參數(shù)“偽類”是必需的,現(xiàn)代瀏覽器已經(jīng)不是必需參數(shù)了
5.兩種寫法: window.getComputedStyle() || document.defaultView.getComputedStyle()
6.IE 不支持 getComputedStyle() 方法,但它有一種類似的概念。在 IE 中,每個具有 style 屬性的元素還有一個 currentStyle 屬性,這個屬性是 CSSStyleDeclaration 的實例,包含當(dāng)前元素全部計算后的樣式
function getStyle(ele) {
return window.getComputedStyle ? window.getComputedStyle(ele) : ele.currentStyle;
}
console.log(getStyle(divEle)); // 返回CSSStyleDeclaration
三、 視口位置
- var rect = element.getBoundingClientRect(無)用于獲取某個元素相對于視口的位置集合。
- 集合中有top, right, bottom, left等屬性。
rect.top: 元素上邊到視口頂部的距離;
rect.right: 元素右邊到視口左邊的距離;
rect.bottom: 元素下邊到視口頂部的距離;
rect.left: 元素左邊到視口左邊的距離
var rect = divEle.getBoundingClientRect();
// 獲取元素的寬高(包括邊框)
var rectWidth = rect.right - rect.left;
var rectHeight = rect.bottom - rect.top;
console.log(rectWidth, rectHeight); // 112 212