標籤:不能 疑惑 strong head 頁面 cti 輸出 height range
在學習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; }
// javascriptvar 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擷取元素樣式值