console.log(document.querySelector(".green").style.backgroundColor);
// gives an empty string as a result in console
.green {
width: 200px;
height: 200px;
background-color: green;
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="src/styles.css">
</head>
<body>
<div class="green"></div>
<script src="src/index.js">
</script>
</body>
</html>
我知道我也可以使用
window.getComputedStyle(document.querySelector(".green")).backgroundColor;
但我想知道其背后的原因,即为什么给出一个空字符串。
.style
仅包含内联样式(通过该属性或具有相同名称的HTML属性设置)。完全不受样式表的影响。getComputedStyle
无论该属性来自何处,都可以获取该属性的当前有效值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句