如何获取SVG组元素的高度/宽度?

24

我需要知道一个SVG元素的宽度和高度?我正在尝试使用以下代码:

$('g#myGroup').height()

...但结果始终为零?

3个回答

46

SVG中的<g>元素没有明确的高度和宽度属性,它们会自动适应其包含的内容。但您可以通过在元素上调用getBBox来获取它们的实际高度/宽度:

var height = document.getElementById("myGroup").getBBox().height;

如果你真的很喜欢jquery,你可以这样编写代码:

$('g#myGroup').get(0).getBBox().height;

根据 Reed Spool 的说法


完美的答案 - 可能可以使用jQuery版本,因为OP正在使用它:$('g#myGroup').get(0).getBBox().height - Reed Spool
@ReedSpool 这不是 jQuery 的版本。.get 只返回 DOM 元素,jQuery 不知道 bbox。 - Willem D'Haeseleer
@WillemD'Haeseleer 我是在指出 $().get() 可以代替更长的 document.getElementById(),因为原问题使用了 jQuery。Robert 正确地采纳了我的建议。 - Reed Spool

4

我无法使上述任何答案起作用,但是我找到了使用d3查找它的解决方案:

var height = d3.select('#myGroup').select('svg').node().getBBox().height;
var width = d3.select('#myGroup').select('svg').node().getBBox().width;

在这里使用getBBox()可以找到组元素的实际宽度和高度,如此简单。


1
我尝试使用getBBox()和getBoundingClientRect()两种方法,但都显示fn未定义。而上面的答案对我来说很有效。Tx - Nisfan

2
基于上述答案,您可以创建jQuery函数.widthSVG()和.heightSVG()。
/*
 * .widthSVG(className)
 * Get the current computed width for the first element in the set of matched SVG elements.
 */

$.fn.widthSVG = function(){
    return ($(this).get(0)) ? $(this).get(0).getBBox().width : null;
};

/*
 * .heightSVG(className)
 * Get the current computed height for the first element in the set of matched SVG elements.
 */
$.fn.heightSVG = function(){
    return ($(this).get(0)) ? $(this).get(0).getBBox().height : null;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接