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

时间:2011-10-01 13:25:46

标签: svg

我需要知道SVG元素的宽度和高度?我试图使用以下内容:

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

...但结果总是为零?

3 个答案:

答案 0 :(得分:44)

svg <g>元素没有明确的高度和宽度属性,它们会根据它们包含的内容自动调整大小。您可以通过在元素上调用getBBox来获取它们的实际高度/宽度:

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

如果你真的喜欢jquery,你可以把它写成

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

根据Reed Spool

答案 1 :(得分:3)

我无法获得上述任何答案,但确实遇到了使用d3找到它的解决方案:

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

getBBox()这里将找到组元素的实际宽度和高度。很简单。

答案 2 :(得分: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;
};