我需要知道一个SVG元素的宽度和高度?我正在尝试使用以下代码:
$('g#myGroup').height()
...但结果始终为零?
我需要知道一个SVG元素的宽度和高度?我正在尝试使用以下代码:
$('g#myGroup').height()
...但结果始终为零?
SVG中的<g>
元素没有明确的高度和宽度属性,它们会自动适应其包含的内容。但您可以通过在元素上调用getBBox来获取它们的实际高度/宽度:
var height = document.getElementById("myGroup").getBBox().height;
如果你真的很喜欢jquery,你可以这样编写代码:
$('g#myGroup').get(0).getBBox().height;
根据 Reed Spool 的说法
我无法使上述任何答案起作用,但是我找到了使用d3查找它的解决方案:
var height = d3.select('#myGroup').select('svg').node().getBBox().height;
var width = d3.select('#myGroup').select('svg').node().getBBox().width;
在这里使用getBBox()可以找到组元素的实际宽度和高度,如此简单。
/*
* .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;
};
.get
只返回 DOM 元素,jQuery 不知道 bbox。 - Willem D'Haeseleer$().get()
可以代替更长的document.getElementById()
,因为原问题使用了 jQuery。Robert 正确地采纳了我的建议。 - Reed Spool