天天看點

JavaScript擷取HTML元素樣式的方法(style、currentStyle、getComputedStyle)

一、style、currentStyle、getComputedStyle的差別

  • style隻能擷取元素的内聯樣式,内部樣式和外部樣式使用style是擷取不到的。
  • currentStyle可以彌補style的不足,但是隻适用于IE。
  • getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome。

"DOM2級樣式" 增強了document.defaultView,提供了getComputedStyle()方法。

 這個方法接受兩個參數:要取得計算樣式的元素和一個僞元素字元串(例如“:after”)。如果不需要僞元素資訊,第二個參數可以是null。

 getComputerStyle()方法傳回一個CSSStyleDeclaration(CSS樣式聲明,如:font-size:12px)對象,其中包含目前元素的所有計算的樣式。

 以下面的HTML頁面為例:

<!DOCTYPE html> 
<html> 
<head> 
    <title>計算元素樣式</title>
    <meta charset="utf-8"> 
    <style> 
        #myDiv { background-color:blue; width:300px; height:200px; } 
    </style> 
    <body> 
        <div id ="myDiv" style="background-color:red; border:1px solid black"></div> 
        <script>     
            var myDiv = document.getElementById("myDiv");     
            var computedStyle = document.defaultView.getComputedStyle(myDiv, null);     
            console.log(computedStyle.backgroundColor);       //"red" 或 rgb(255, 0, 0)    
            console.log(computedStyle.width);                 //"100px"     
            console.log(computedStyle.height);                //"200px"   
            console.log(computedStyle.border);                //"1px solid rgb(0, 0, 0)" 或 空字元串
        </script>
</body> 
</head> 
</html>      

邊框屬性可能也不會傳回樣式表中實際的border規則(Opera會傳回,但其它浏覽器不會)。

存在這個差别的原因是不同浏覽器解釋綜合屬性的方式不同,因為設定這種屬性實際上會涉及很多其他的屬性。

在設定border時,實際上是設定了四個邊的邊框寬度、顔色、樣式屬性。

是以,即使 computedStyle.border不會在所有浏覽器中都傳回值,但computedStyle.borderLeftWidth則會傳回值。

二、封裝getStyle (擷取樣式currentStyle getComputedStyle相容處理)

2.1基礎版:

<script type="text/javascript">
    function getStyle(obj, attr){
         if(obj.currentStyle){
            return obj.currentStyle[attr];
         }
         else{
            return getComputedStyle(obj, null)[attr];
         }
    }
    window.onload = function (){
        var oDiv = document.getElementById('div1');
        alert(getStyle(oDiv, 'backgroundColor'));
    }
</script>

<div id="div1"></div>

      

2.2簡潔版:

function getStyle(obj, attr) {
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
}      

文章參考:http://www.candoudou.com/archives/526

     http://www.cnblogs.com/leejersey/archive/2012/08/16/2642604.html

轉載于:https://www.cnblogs.com/lvmylife/p/5387558.html

繼續閱讀