Window.getComputedStyle不显示内联样式

时间:2017-03-03 21:10:49

标签: javascript css svg

我有这样简单的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>

当我使用:window.getComputedStyle(document.getElementById('rect'))时,我将widthheight的值都设为auto而不是100px,就像我预期的那样。< / p>

这是怎么回事?如果是这样,我怎样才能让它返回100px?

我需要使用此函数将外部css中定义的所有样式转换为svg元素的内联样式属性,以便稍后可以将其导出。

2 个答案:

答案 0 :(得分:0)

您可以使用document.getElementById('rect').style.heightdocument.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;
}, {});

JSFiddle

答案 1 :(得分:0)

window.document.getElementById('rect').style.width将返回内联css width属性。

尝试打击代码

&#13;
&#13;
var rect = window.document.getElementById('rect');
console.log(rect.style.width);
&#13;
<!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>
&#13;
&#13;
&#13;

相关问题