獲取元素計算樣式getComputedStyle()與currentStyle

window.getComputedStyle()方法是標準化接口,返回一個對象,該對象在應用活動樣式表並解析這些值可能包含的任何基本計算後報告元素的全部CSS屬性的值。 私有的CSS屬性值能夠經過對象提供的API或經過簡單地使用CSS屬性名稱進行索引來訪問。javascript

目前主流瀏覽器均支持getComputedStyle()獲取元素計算樣式。html

語法:java

getComputedStyle(element [,pseudoElt])瀏覽器

element測試

用於獲取計算樣式的Element。htm

pseudoElt對象

可選blog

指定一個要匹配的僞元素的字符串。必須對普通元素省略(或null)。索引

案例:接口

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        h3::after {
            content: "rocks!";
        }
    </style>

</head>

<body>

    <h3>generated content</h3>
    <script>
        let h3 = document.querySelector('h3'),
            result = getComputedStyle(h3, '::after').content;

        console.log(`the generated content is: ${result}`);
        //=> the generated content is: "rocks!"
     
    </script>
</body>

</html>

  

參考文獻:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

currentStyle是微軟推出的針對IE瀏覽器的標準,並不是標準接口,主要是對IE8及如下版本支持該屬性。

語法:

elementget.currentStyle

微軟開發文檔參考:

https://docs.microsoft.com/en-us/previous-versions//ms528441(v=vs.85)

實際開發過程當中,若須要考慮二者的兼容性:

/*obj爲元素DOM,name爲元素屬性,類型爲字符串。能夠經過360瀏覽器能夠單獨測試IE瀏覽器下的狀況。
 *
 */
function getStyle(obj, name) {
    if (obj.currentStyle) {
        return obj.currentStyle[name];
    } else {
        return getComputedStyle(obj, null)[name];
    }
}
相關文章
相關標籤/搜索