【发布时间】:2018-01-12 01:27:31
【问题描述】:
我需要知道 SVG 元素的宽度和高度?我尝试使用以下内容:
$('g#myGroup').height()
...但结果总是为零?
【问题讨论】:
标签: svg
我需要知道 SVG 元素的宽度和高度?我尝试使用以下内容:
$('g#myGroup').height()
...但结果总是为零?
【问题讨论】:
标签: svg
svg <g> 元素没有明确的高度和宽度属性,它们会自动调整大小到它们包含的任何内容。您可以通过在元素上调用 getBBox 来获取它们的实际高度/宽度:
var height = document.getElementById("myGroup").getBBox().height;
如果你真的很喜欢 jquery,你可以把它写成
$('g#myGroup').get(0).getBBox().height;
根据 Reed Spool
【讨论】:
.get只是返回DOM元素,jquery不知道bbox。
$().get() 而不是更长的document.getElementById(),因为原始问题使用了jQuery。罗伯特正确地采纳了我的建议。
我无法获得上述任何答案,但确实遇到了使用 d3 找到它的解决方案:
var height = d3.select('#myGroup').select('svg').node().getBBox().height;
var width = d3.select('#myGroup').select('svg').node().getBBox().width;
getBBox() 在这里会找到组元素的实际宽度和高度。就这么简单。
【讨论】:
根据上面的回答,你可以创建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;
};
【讨论】: