javascript - 如何获取 svg :g element 的宽度

标签 javascript jquery svg width

我目前正在使用 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);

但它给了我零。我怎么能在我的浏览器上的黄色工具提示框中看到它 enter image description here

当我选择这一行时。

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

最佳答案

试试 .getBoundingClientRect

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

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

关于javascript - 如何获取 svg :g element 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11702952/

相关文章:

javascript - 在 SVG 元素中使用类似数组的对象(节点列表) - d3 Javascript

javascript - Browserify - 找不到变量 : require

javascript - 使用 sails.js 编写密码重置

javascript - 单击链接时跳过更改位置

jquery - 将 json 列表传递给 MVC 3

javascript - 使用jquery检查页面高度

javascript - 使用 jQuery 创建悬停和单击功能的精益方法到 SVG 目录映射

javascript - 使用 javascript 更改 React 应用程序的输入文本

javascript - 如何使用 jquery 选项卡加载多个菜单

javascript - 如何在 d3 v4 中使用 d3.transform?