繁体   English   中英

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

[英]how to get information from a svg string in javascript?

我有一个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层中仅选择矩形的高度? 感谢您的回答

尝试这个?

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

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

使用字符串:

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

使用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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM