繁体   English   中英

JavaScript没有看到backgroundColor?

[英]JavaScript doesn't see a backgroundColor?

为什么我看不到自己的风格?

    <style>
        .style{
            background-color: pink;
            top: 50px;
            left: 50px;
        }
    </style>
    <script>
        window.onload = function () {
            console.log(document.querySelector('.style').style.backgroundColor);
        }
    </script>
    </head>
    <body><div class="style">A</div></body>

JS无法看到带样式的块的接缝。

这不是element.style工作方式。 el.style只从元素的style属性中获取,所以如果它有一个style="background-color: red" ,它只会看到backgroundColor

你想要window.getComputedStyle()

var el = document.querySelector('.style');
var bg = getComputedStyle(el).backgroundColor;

您可以在控制台中尝试此页面:

getComputedStyle(document.querySelector('pre')).backgroundColor

速度:

el = document.querySelector('pre');
console.time('getComputedStyle');
for (i=0; i<1000; i++) c = getComputedStyle(el).backgroundColor;
console.timeEnd('getComputedStyle');

收益:

getComputedStyle: 9.120ms

60帧/秒的1帧是16毫秒,所以每帧可以做~2000个getComputedStyle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM