如何从javascript中的SVG字符串获取信息

how to get information from a svg string in javascript?

本文关键字:字符串 获取 信息 SVG 中的 javascript      更新时间:2023-09-26

我有一个svg绘图的字符串。例如,我的字符串var有这样的内容:

<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>

是否有一种简单的方法来获取信息?例如,获得矩形高度的最佳方法是什么?如何选择仅从第2层的矩形的高度?谢谢你的回答

使用XML dom解析器。
正如其他答案所述,jQuery是操作和遍历html/xml的一个非常好的解决方案:

 $(svgString).find('g:eq(1) rect').attr('height');   

如果你不想使用第三方库,你可以在纯javascript中做到这一点,但你的svg字符串应该追加到dom:

var svgString = a='<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>',
    tempElement = document.createElement('div');
tempElement.innerHTML = svgString;
var height = tempElement.querySelector('g:nth-child(1) rect').getAttribute('height'); 

下面是一个工作演示:http://jsfiddle.net/gion_13/5K5x2/

试一下?

在代码中包含jQuery,并使用:

$("svg").find("rect").attr("height");

使用字符串

:

var str = "<svg> ... </svg>"
$(str).find("rect").attr("height");