javascript 獲取元素樣式必殺技
Javascript獲取CSS屬性值方法:getComputedStyle和currentStyle
1 .對于元素的內聯(lián)CSS樣式(<div style="color:#369">hello</div>),可以直接使用element.style.color來直接獲取css屬性的值;
2. 但是對于外部定義的css樣式使用這種方式就無法獲取了,而且IE瀏覽器和其他標準瀏覽器(Firefox,Chrome,Opera,Safari)使用的方法不一樣,IE瀏覽器使用element.currentStyle,W3C標準瀏覽器使用getComputedStyle來獲取。
1. IE獲取元素外部定義的CSS屬性值: element.currentStyle
currentStyle對象返回了元素上的樣式表,但是style對象只返回通過style標簽屬性應用到元素的內嵌樣式。
因此,通過currentStyle對象獲取的樣式值可能與通過style對象獲取的樣式值不同。
例如,如果段落的color屬性值通過鏈接或嵌入樣式表設置為紅色( red ),而不是內嵌的話,對象.currentStyle.color 將返回正確的顏色,而對象style.color不能返回值。但是,如果用戶指定了 <P STYLE="color:'red'">,currentStyle和STYLE對象都將返回值 red。
currentStyle對象反映了樣式表中的樣式優(yōu)先順序。在 HTML 中此順序為:
1) 內嵌樣式
2) 樣式表規(guī)則
3) HTML 標簽屬性
4) HTML 標簽的內部定義
2. W3C獲取元素外部定義的CSS屬性值: window.getComputedStyle(element, pseudoElt)
element必選,HTML元素
pseudoElt必選,獲取該元素的偽類樣式
function getStyle(node, property){
if (node.style[property]) {
return node.style[property];
}
else if (node.currentStyle) {
return node.currentStyle[property];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(node, null);
return style.getPropertyValue(property);
}
return null;
}
相關文章
JavaScript 函數(shù)用法詳解【函數(shù)定義、參數(shù)、綁定、作用域、閉包等】
這篇文章主要介紹了JavaScript 函數(shù)用法,結合實例形式分析了JavaScript函數(shù)定義、參數(shù)、綁定、作用域、閉包、回調函數(shù)、柯理化函數(shù)等相關概念、原理與操作注意事項,需要的朋友可以參考下2020-05-05javascript為下拉列表動態(tài)添加數(shù)據(jù)項
這篇文章主要介紹了javascript如何為下拉列表動態(tài)添加數(shù)據(jù)項,需要的朋友可以參考下2014-05-05