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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11702952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:47:14  来源:igfitidea点击:

How to get the width of an svg:g element

javascriptjquerysvgwidth

提问by A_user

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

我目前正在使用svgJavaScript 中的一个元素。我是新手。

My question is that I have an svgelement in which I have multiple svg:gelements. And in my svg:gelements 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>

gare dynamically appending in my

g动态附加在我的

g "my_class"

g "my_class"

Now I want to set my svgwidth equal to the width of g.my_classwidth.

现在我想将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 boxenter image description here

但它给了我零。我怎么能在我的浏览器的黄色工具提示框中看到它在此处输入图片说明

when I select this line.

当我选择这条线时。

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

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

回答by Esailija

Try .getBoundingClientRect

尝试 .getBoundingClientRect

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

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

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

回答by Erik Dahlstr?m

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/