为什么我看不到自己的风格?
<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>
Run Code Online (Sandbox Code Playgroud)
JS无法看到带样式的块的接缝.
那不是多么element.style有效.el.style只取得元素的样式属性,所以它只会看到backgroundColor它是否有style="background-color: red".
var el = document.querySelector('.style');
var bg = getComputedStyle(el).backgroundColor;
Run Code Online (Sandbox Code Playgroud)
您可以在控制台中尝试此页面:
getComputedStyle(document.querySelector('pre')).backgroundColor
Run Code Online (Sandbox Code Playgroud)
速度:
el = document.querySelector('pre');
console.time('getComputedStyle');
for (i=0; i<1000; i++) c = getComputedStyle(el).backgroundColor;
console.timeEnd('getComputedStyle');
Run Code Online (Sandbox Code Playgroud)
收益:
getComputedStyle: 9.120ms
Run Code Online (Sandbox Code Playgroud)
60帧/秒的1帧是16毫秒,因此getComputedStyle每帧可以做~2000 秒.
| 归档时间: |
|
| 查看次数: |
35 次 |
| 最近记录: |