在 svg 字符串中使用 getBoundingClientRect、getBBox?

anr*_*raT -1 jquery svg

嗨,我有下一个 svg 字符串 str=

<svg width="612" height="394" xmlns="http://www.w3.org/2000/svg">
 <g>
     <title>Layer 1</title>
     <rect id="svg_1" height="152" width="265" y="44" x="91" stroke-width="5" stroke="#000000" fill="#FF0000"/>
 </g>
 <g>
     <title>Layer 2</title>
     <rect id="svg_2" height="125" width="151" y="157" x="399" stroke-width="5" stroke="#000000" fill="#FF0000"/>
 </g>
</svg>
Run Code Online (Sandbox Code Playgroud)

为了获得第一个矩形的宽度和高度,我可以使用 javascript+jquery:

alert("width:"+$(str).find('g:eq(0) rect:eq(0)').attr('width'));
alert("height:"+$(str).find('g:eq(0) rect:eq(0)').attr('height'));
Run Code Online (Sandbox Code Playgroud)

我想找到相同的使用 .getBoundingClientRect() 或 .getBBox() 我试过:

alert("height"+$(str).find('g:eq(0) rect:eq(0)').getBoundingClientRect().width);
alert("height"+$(str).find('g:eq(0) rect:eq(0)').getBBox().width);
Run Code Online (Sandbox Code Playgroud)

但它不起作用。有谁知道解决方案?我该如何使用 getBoundingClientRect 和 getBBox 以及我的字符串 str?谢谢

met*_*ion 5

jQuery 返回一个 jQuery 对象,您需要实际的 DOM 元素。为此,您只需[0]在选择器后添加:

alert("height"+$(str).find('g:eq(0) rect:eq(0)')[0].getBoundingClientRect().width);
alert("height"+$(str).find('g:eq(0) rect:eq(0)')[0].getBBox().width);
Run Code Online (Sandbox Code Playgroud)

请注意,要获取维度,必须将元素添加到 DOM,它不应该只是一个字符串。

此外,一种更快、更优雅的方法是......

//no need to indicate the first element since querySelector already does this;
var el = str.querySelector('g rect');
alert( "width: " + el.getBoundingClientRect().width );
alert( "width: " + el.getBBox().width );
Run Code Online (Sandbox Code Playgroud)