0
点赞
收藏
分享

微信扫一扫

window.getComputedStyle()

小暴龙要抱抱 2022-04-23 阅读 65

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

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

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

<!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>


举报

相关推荐

0 条评论