window.getComputedStyle()

window.getComputedStyle()方法返回一个 CSSStyleDeclaration 对象,与 style 属性的类型相同,其中包含元素的计算样式;
用法如下:

document.defaultView.getComputedStyle(element, [pseudo-element])

// or
window.getComputedStyle(element, [pseudo-element])

说明:
element 用于获取计算样式的Element。
pseudoElt 可选指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)

<!DOCTYPE html>
<html>

<head>
    <style type="text/css">
        #root {
    
    
            background-color: pink;
            width: 100px;
            height: 200px;
        }

        #root::after {
    
    
            content: 'Haskell';
            display: table;
            clear: both;
        }
    </style>
</head>

<body>
    <div id="root" style="background-color: rgb(135, 206, 235);"></div>
</body>
<script>
    function getStyleByAttr(node, name) {
    
    
        return window.getComputedStyle(node, null)[name]
    }

    const node = document.getElementById('root')

    // rgb(135, 206, 235)
    console.log(getStyleByAttr(node, 'backgroundColor'))

    // 100px
    console.log(getStyleByAttr(node, 'width'))

    // 200px
    console.log(getStyleByAttr(node, 'height'))

    // table
    console.log(window.getComputedStyle(node, '::after').display)

    // Haskell
    console.log(window.getComputedStyle(node, '::after').content)
</script>

</html>


猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/124369477