【问题标题】:How does one get the height/width of an SVG group element?如何获得 SVG 组元素的高度/宽度?
【发布时间】:2018-01-12 01:27:31
【问题描述】:

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

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

...但结果总是为零?

【问题讨论】:

    标签: svg


    【解决方案1】:

    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
    • @ReedSpool 这不是 jQuery 版本。 .get只是返回DOM元素,jquery不知道bbox。
    • @WillemD'Haeseleer 我指出可以使用$().get() 而不是更长的document.getElementById(),因为原始问题使用了jQuery。罗伯特正确地采纳了我的建议。
    【解决方案2】:

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

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

    getBBox() 在这里会找到组元素的实际宽度和高度。就这么简单。

    【讨论】:

    • 我尝试了 getBBox() 和 getBoundingClientRect()。两者都显示 fn 未定义。上面的答案对我来说很好。发送
    【解决方案3】:

    根据上面的回答,你可以创建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;
    };
    

    【讨论】:

      猜你喜欢
      • 2013-08-11
      • 2019-04-11
      • 2021-04-03
      • 1970-01-01
      • 2015-12-24
      • 2010-09-29
      • 2016-11-04
      • 2016-12-10
      相关资源
      最近更新 更多