JavaScript没有';你看不到背景色吗?
为什么我看不到我的风格JavaScript没有';你看不到背景色吗?,javascript,Javascript,为什么我看不到我的风格 <style> .style{ background-color: pink; top: 50px; left: 50px; } </style> <script> window.onload = function () { console.log(document.qu
<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>
.风格{
背景颜色:粉红色;
顶部:50px;
左:50px;
}
window.onload=函数(){
log(document.querySelector('.style').style.backgroundColor);
}
A.
JS无法看到具有样式的块的接缝 这不是
element.style
的工作方式el.style
仅从元素的style属性中获取,因此如果元素具有style=“background color:red”
,则只能看到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');
每秒60帧的1帧是16毫秒,因此每帧可以执行~2000
getComputedStyle
s。但是getComputedStyle是一项繁重的操作。有些人说,最好不要使用它。当然,每次通话0.03毫秒就很重。(我猜)不过你可以在一个框架内完成很多。这都是相对的。不要将其与.style
access进行比较。在一些浏览器中尝试一下。
el = document.querySelector('pre');
console.time('getComputedStyle');
for (i=0; i<1000; i++) c = getComputedStyle(el).backgroundColor;
console.timeEnd('getComputedStyle');
getComputedStyle: 9.120ms