JavaScript獲取元素css屬性


1 window.getComputedStyle(非IE)

語法

let styles = window.getComputedStyle(Element, [pseudoElt]);

該方法一共有兩個參數,其中第一個為必須參數,第二個參數為可選參數,為空時會默認為null.

Element:需要計算樣式的元素.注第一個參數必須是Element對象(傳遞一個非節點元素,如 一個#text 節點, 將會拋出一個錯誤).

pseudoElt:偽類元素的字符串.表示指定元素節點的偽元素(:before、:after、:first-line、:first-letter等)默認值為null.

注意事項

Window.getComputedStyle()方法返回一個對象,該對象在應用活動樣式表並解析這些值可能包含的任何基本計算后報告元素的所有CSS屬性的值。

注:

  • Window.getComputedStyle()方法返回的style是一個實時的 CSSStyleDeclaration 對象,當元素的樣式更改時,它會自動更新本身。
  • Window.getComputedStyle()方法返回的對象style屬性為只讀,不能更改.

獲取樣式表中的樣式

let style = window.getComputedStyle(Element, [pseudoElt]).getPropertyValue(property)

let style = window.getComputedStyle(Element, [pseudoElt]).property

let style = window.getComputedStyle(Element, [pseudoElt])[property]

注:獲取元素的的樣式時會獲取該屬性的全部值,有時會帶單位,需要進行特殊處理,可以使用parseFloat( ).

2 Element.currentStyle(XIE)

語法

let styles = Element.currentStyle;

該方法不需要參數,需要計算樣式的元素直接調用.

Element:必須參數.不可省略.

獲取樣式表中的樣式

let style = Element.currentStyle.getAttribute(property)

let style = Element.currentStyle.property

let style = Element.currentStyle[property]

注:

perperty必須采用駝峰式的寫法。如果需要獲取 font-size 屬性,那么傳入的參數應該是 fontSize。因此在IE 中要獲得單個屬性的值,就必須將屬性名轉為駝峰形式。

3 Element.style.property

語法

let style = Element.style.property

Element:需要計算樣式的元素. 

property:元素中需要獲取的屬性.

注意事項

  •  該方法返回元素中屬性的值,該方法可以讀取可以賦值.
  •  該方法只能獲取元素內聯樣式表中的樣式,不能獲取內部和外部的樣式表.

4 使用方法

 方法一:封裝成函數

 function getStyle(Element,Property){
       return Element.currentStyle ? Element.currentStyle[Property] : getComputedStyle(ELement)[Property];
 }
 
 var oDiv = document.getElementById("test");
 alert(getStyle(oDiv,"top"));
參考自:https://www.cnblogs.com/jing-tian/p/10810181.html#4344496

 

方法二:IF語句判斷

if (window.getComputedStyle) {
       style  = parseInt(getComputedStyle(Element)[Property])
} else {
        style = parseInt(Element.currentStyle[Property])
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM