获取元素计算样式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];
    }
}
相关文章
相关标签/搜索