1. 程式人生 > >js中currentStyle和getComputedStyle獲取css樣式區別

js中currentStyle和getComputedStyle獲取css樣式區別

js中獲取樣式我瞭解到三種。一種是通過obj.offsetAttr來獲取樣式,通過這種方法來獲取元素的寬高時,如果沒有邊框,可以正確獲取,如果使用邊框屬性則會出現問題,為了解決這個問題,可以使用另一種方法,通過getComputedStyle屬性來獲取css樣式(非行間)。還有一種是通style屬性來獲取css樣式(行間)。

先看程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>document</title
>
<style> #clock { width:200px; height:200px; background:yellow; } </style> <script> window.onload=function(){ var oDiv=document.getElementById("clock"); alert(getStyle(oDiv,"width")); } /*可以作為一段標準程式碼,理解並記憶(個人建議)*/
function getStyle(obj,attr) { if(obj.currentStyle) { return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,false)[attr]; } }
</script> </head> <body> <div id="clock"
>
</div> </body> </html>

接下來解釋一下:

getComputedStyle用來獲取css樣式屬性,只讀。有人可能問了,既然有了這個,那為什麼還用currentStyle,這當然要問IE(就它最特殊)了,這個是針對IE瀏覽器使用的。於是為了相容主流瀏覽器,就可以將這兩個封裝成getStyle函式。這個主要是獲取非行間樣式,也就是像位於之間的css樣式屬性。

當然不要忘記了還有style屬性。程式碼奉上:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>document</title>
    <script>
        window.onload=function(){
            var oDiv=document.getElementById("clock");
            alert(oDiv.style.width);
        }
    </script>
</head>
<body>
    <div id="clock"  style="width:200px;height:200px;background-color:yellow "></div>


</body>
</html>

解釋一下:

style只能獲取行間樣式,也就是style=”……”後面的屬性。如果將style=”……”裡面的內容設定成css樣式也就是

#clock {
    width:200px;
    height:200px;
    background:yellow;
}

將獲取不到任何內容。

style屬性的最大作用是用來設定css屬性而不是獲取css屬性,例如:

oDiv.style.width=400+'px';

設定該元素的寬度為400px。