我目前正在使用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“my_class”
现在我想将svg
宽度设置为g.my_class
宽度的宽度。
var svgWidth = $('.my-class').width()
alert(svgWidth);
但它给我零。我怎么能在我的浏览器上用黄色工具提示框
看到它当我选择这一行时。
有人可以指导我吗?我这样做是对的,或者我怎样才能做到这一点? 感谢
答案 0 :(得分:86)
我建议getBBox
(这是SVG 1.1的一部分)超过getBoundingClientRect
(不是):
$('.my-class')[0].getBBox().width;
答案 1 :(得分:80)
尝试.getBoundingClientRect
$('.my-class')[0].getBoundingClientRect().width;