简体   繁体   English

如何获取 svg:g 元素的宽度

[英]How to get the width of an svg:g element

I am currently working with an svg element in JavaScript.我目前正在使用 JavaScript 中的svg元素。 And I am new to this.我是新手。

My question is that I have an svg element in which I have multiple svg:g elements.我的问题是我有一个svg元素,其中有多个svg:g元素。 And in my svg:g elements I have various other svg elements.在我的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动态附加在我的

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我怎么能在我的浏览器的黄色工具提示框中看到它在此处输入图片说明

when I select this line.当我选择这条线时。

Can anyone kindly guide me?任何人都可以指导我吗? Am I doing this right, or how can I achieve this?我这样做对吗,或者我怎样才能做到这一点? Thanks谢谢

Try .getBoundingClientRect尝试.getBoundingClientRect

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

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

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM