我有这样一个简单的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'))时,我得到width和height的值都是auto,而不是我期望的100px。
事情应该是这样的吗?如果是这样,我怎么才能返回100px呢?
我需要此函数将外部css中定义的所有样式转换为svg元素的内联样式属性,以便稍后导出。
发布于 2017-03-04 05:34:50
您可以只使用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;
}, {});发布于 2017-03-04 05:36:26
window.document.getElementById('rect').style.width将返回内联css width属性。
试试blow代码
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>
https://stackoverflow.com/questions/42588485
复制相似问题