Window.getComputedStyle不显示嵌入式样式
问题描述:
我有简单的HTML这样的:Window.getComputedStyle不显示嵌入式样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<svg id="svg" viewBox="0 0 594 600" preserveAspectRatio="xMinYMin meet">
<rect id="rect" fill="#98df8a" style="width: 100px; height: 100px;">
</rect>
</svg>
</body>
</html>
当我使用:window.getComputedStyle(document.getElementById('rect'))
,我得到两个width
和height
的价值是auto
,而不是像100px
我期望的。
这是怎么回事?如果是这样,我怎么能使它返回100px?
我需要此函数将外部CSS中定义的所有样式转换为svg元素的内联样式属性,以便稍后可以导出它。
答
你可以只使用document.getElementById('rect').style.height
和document.getElementById('rect').style.width
,如果你要处理的东西款式任意名单如下:
var exportStyleKeys = ['width', 'height'];
var rect = document.getElementById('rect');
var exportStyles = exportStyleKeys.reduce((styles, styleKey) => {
styles[styleKey] = rect.style[styleKey];
return styles;
}, {});
答
window.document.getElementById('rect').style.width
将返回内联CSS width属性。
尝试打击代码
var rect = window.document.getElementById('rect');
console.log(rect.style.width);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<svg id="svg" viewBox="0 0 594 600" preserveAspectRatio="xMinYMin meet">
<rect id="rect" fill="#98df8a" style="width: 100px; height: 100px;">
</rect>
</svg>
</body>
</html>