[英]Window.getComputedStyle does not show inline style
I have simple html like this: 我有这样的简单html:
<!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>
When i use: window.getComputedStyle(document.getElementById('rect'))
, I get the value of both width
and height
to be auto
and not 100px
like what I expected. 当我使用:
window.getComputedStyle(document.getElementById('rect'))
,我得到的width
和height
的值都是auto
而不是100px
期望值。
Is this how it should be? 这是应该的吗? If so, how can i make it to return 100px ?
如果是这样,我如何使其返回100px?
I need this function to turn all my styles defined in the external css into inline style attribute for svg elements so that I can export it later. 我需要此函数将我在外部CSS中定义的所有样式都转换为svg元素的内联样式属性,以便以后可以将其导出。
You could just use document.getElementById('rect').style.height
and document.getElementById('rect').style.width
and if you want to handle an arbitrary list of styles something like this: 您可以只使用
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
will return you the inline css width attribute. window.document.getElementById('rect').style.width
将返回内联css width属性。
Try the blow code 尝试打击代码
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.