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
How to get the width of an svg:g element
提问by A_user
I am currently working with an svg
element in JavaScript. And I am new to this.
我目前正在使用svg
JavaScript 中的一个元素。我是新手。
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
动态附加在我的
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
任何人都可以指导我吗?我这样做对吗,或者我怎样才能做到这一点?谢谢
回答by Esailija
Try .getBoundingClientRect
尝试 .getBoundingClientRect
$('.my-class')[0].getBoundingClientRect().width;
回答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;