原生js獲取元素樣式值
阿新 • • 發佈:2017-08-25
應該 eight current document 疑惑 行內樣式 lin script 輸出
在學習js初期,就一直有一個疑問,獲取元素樣式的值,不是直接使用obj.style.left
之類的就可以得到了嗎?可是使用這樣的方式,有的時候能夠獲取得到,有的時候又不能獲取,一直疑惑不已,但是由於以前學習態度的問題,也沒有深究,今天專門花了點時間整理了一下這方面的知識。
樣式
首先,我們要明確樣式的種類有以下三種
- 內聯樣式: 也就是行內樣式,直接寫在DOM元素的style屬性中
- 嵌入樣式: 寫在html頁面中的<style></style>中的樣式
-
外部樣式: 由link標簽引入的css文件中的樣式
優先級:內聯 > 嵌入 > 外部
首先,先寫一個例子來測試一下通過style方法獲取元素樣式的值,思路是,一個樣式寫在行內,一個樣式寫在style標簽中,一個樣式由link引入
<head> <meta charset="UTF-8"> <title>get style</title> <style> <!-- 嵌入樣式 --> .box { height: 200px; } </style> <!-- 引入外部樣式 --> <link rel="stylesheet" href="./index.css"> </head> <body> <!-- 行內樣式 --> <div class="box" style="width: 100px;"></div> </body>
// index.css
.box { background-color: orange; }
// javascript
var box = document.getElementsByClassName(‘box‘)[0];
console.log(box.style.width);
console.log(box.style.height);
console.log(box.style.backgroundColor);
得到的結果為:
‘100px‘
‘‘
‘‘
因此我們可以看到height值和backgroundColor值沒有被獲取到,所以我們得到以下結論:
style只能獲取行內樣式的值,無法獲取嵌入式樣式和外部樣式的值
那麽嵌入式樣式和外部樣式的值應該怎麽辦呢,看下面代碼
// currentStyle: IE下獲取元素樣式的值
if ( box.currentStyle ) {
console.log( ‘this is IE.‘ );
console.log( box.currentStyle.width );
console.log( box.currentStyle.height );
console.log( box.currentStyle.backgroundColor );
} else {
// chorme and firefox
console.log( document.defaultView.getComputedStyle(box, false).width );
console.log( document.defaultView.getComputedStyle(box, fasle).height );
console.log( document.defaultView.getComputedStyle(box, false).backgroundColor );
}
輸出結果
‘this is IE.‘
‘100px‘
‘200px‘
‘orange‘
分別在IE, chrome, firefox下測試一下,最後都能夠獲取所有的屬性。非常好,於是我們可以得出結論
獲取元素樣式值的最佳方式,就是通過obj.currentStyle
或者document.defaultView.getComputedStyle( obj, false )
的方式,其中前者適用於IE,後者適用於chrome和Firefox
因此我們可以寫一個獲取元素樣式值的方法
var getStyle = function(obj, key) {
return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle( obj, false )[key];
}
原生js獲取元素樣式值