window.getComputedStyle()方法返回一个 CSSStyleDeclaration 对象,与 style 属性的类型相同,其中包含元素的计算样式; 用法如下:
document.defaultView.getComputedStyle(element, [pseudo-element])
window.getComputedStyle(element, [pseudo-element])
说明: element 用于获取计算样式的Element。 pseudoElt 可选指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)
<!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')
console.log(getStyleByAttr(node, 'backgroundColor'))
console.log(getStyleByAttr(node, 'width'))
console.log(getStyleByAttr(node, 'height'))
console.log(window.getComputedStyle(node, '::after').display)
console.log(window.getComputedStyle(node, '::after').content)
</script>
</html>
|