【问题标题】:How to get the width of an svg:g element如何获取 svg:g 元素的宽度
【发布时间】:2012-07-27 00:37:43
【问题描述】:

我目前正在使用 JavaScript 中的 svg 元素。我是新手。

我的问题是我有一个 svg 元素,其中我有多个 svg:g 元素。在我的 svg:g 元素中,我还有其他各种 svg 元素。

    <svg>
     <g class="my-class">
      <g class "c1">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
      <g class="c2">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
      <g class="c3">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
    </g>
   </svg>

g 动态附加到我的

g“我的班级”

现在我想将svg 的宽度设置为等于g.my_class 的宽度。

var svgWidth  =   $('.my-class').width()
alert(svgWidth);

但它给了我零。我怎么能在浏览器的黄色工具提示框中看到它

当我选择这一行时。

有人可以指导我吗?我这样做对吗,或者我怎样才能做到这一点? 谢谢

【问题讨论】:

    标签: javascript jquery svg width


    【解决方案1】:

    试试.getBoundingClientRect

    $('.my-class')[0].getBoundingClientRect().width;
    

    演示http://jsfiddle.net/5DA45/

    【讨论】:

    • 非常感谢@Esailija。但我想问一件事,它给我的宽度值等于 10 + 工具提示框中的宽度值。知道为什么会这样
    • 感谢@Esailija 的工作,是的,我更喜欢getBoundingClientRect() 而不是getBBox()。原因是当我需要“g”的宽度时,我需要根据 SVG 测量的实际宽度。而 getBBox() 为我们提供了基于 Viewbox 大小的宽度,无论 SVG 的大小如何。即使我将 SVG 的大小调整为 12px(视图框大小为“0 0 409.215 550.197”)getBBox() 给我 4.09.215 而我需要 SVG 的原始大小应该是“8.920745849609375”所以 getBBox 并不是真正有用的功能SVG 中 g 的大小。
    • 所以高度使用 $('.my-class')[0].getBoundingClientRect().height;
    【解决方案2】:

    我会推荐 getBBox(它是 SVG 1.1 的一部分)而不是 getBoundingClientRect(它不是):

    $('.my-class')[0].getBBox().width;
    

    演示http://jsfiddle.net/TAck4/

    【讨论】:

    • 为什么你会推荐它?
    • 就像它说的那样,因为 getBBox 是 SVG 规范的必需部分,而 getBoundingClientRect 不是。
    • @Yarin - 另外,请注意,只有 getBBox 获得 svg 内左上角的正确坐标(-20,-10):jsfiddle.net/QGN6c/20
    • 请注意,getBBox 返回的值是 SVG 坐标,而 getBoundingClientRect 返回渲染坐标。在带有 viewBox 而不是宽度和高度的 SVG 中,返回的值可能不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2011-06-08
    • 1970-01-01
    • 2017-01-30
    • 2015-10-17
    相关资源
    最近更新 更多