如何获得svg的宽度:g元素?

时间:2022-10-27 12:38:34

I am currently working with an svg element in JavaScript. And I am new to this.

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

My question is that I have an svg element in which I have multiple svg:g elements. And in my svg:g elements I have various other svg elements.

我的问题是,我有一个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 are dynamically appending in my

g在my中是动态附加的

g "my_class"

g“my_class”

Now I want to set my svg width equal to the width of g.my_class width.

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

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

But its giving me zero. How ever I can see it on my browser in a yellow tool tip box如何获得svg的宽度:g元素?

但结果是0。我怎么能在浏览器的黄色工具提示框中看到它呢

when I select this line.

当我选择这一行。

Can anyone kindly guide me? Am I doing this right, or how can I achieve this? Thanks

谁能指点我一下吗?我做得对吗?或者我怎样才能做到?谢谢

2 个解决方案

#1


73  

Try .getBoundingClientRect

尝试.getBoundingClientRect

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

Demo http://jsfiddle.net/5DA45/

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

#2


82  

I'd recommend getBBox (which is part of SVG 1.1) over getBoundingClientRect (which isn't):

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

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

Demo http://jsfiddle.net/TAck4/

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

#1


73  

Try .getBoundingClientRect

尝试.getBoundingClientRect

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

Demo http://jsfiddle.net/5DA45/

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

#2


82  

I'd recommend getBBox (which is part of SVG 1.1) over getBoundingClientRect (which isn't):

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

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

Demo http://jsfiddle.net/TAck4/

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