如何获得SVG组元素的高度/宽度?
问题描述:
我需要知道SVG元素的宽度和高度吗?我正在尝试使用以下内容:
I need to know the width and height of a SVG element? Im trying to use the following:
$('g#myGroup').height()
...但是结果总是为零?
...but the result is always zero?
答
svg <g>
元素没有显式的height和width属性,它们会自动调整大小以包含它们所包含的内容.您可以通过在元素上调用getBBox来获取它们的实际高度/宽度:
svg <g>
elements don't have explicit height and width attributes, they auto size to whatever they contain. You can get their actual height/width by calling getBBox on the element though:
var height = document.getElementById("myGroup").getBBox().height;
如果您真的很喜欢jquery,可以将其写为
If you're really into jquery you could write it as
$('g#myGroup').get(0).getBBox().height;
根据Reed Spool
according to Reed Spool