如何从javascript中的svg字符串获取信息? [英] how to get information from a svg string in javascript?

查看:90
本文介绍了如何从javascript中的svg字符串获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 svg 绘图的字符串.例如,我的字符串 var 具有以下内容:

<g><title>第 1 层</title><rect id="svg_1" height="152" width="265" y="44" x="91" stroke-width="5" stroke="#000000" fill="#FF0000"/><g><title>第 2 层</title><rect id="svg_2" height="125" width="151" y="157" x="399" stroke-width="5" stroke="#000000" fill="#FF0000"/></svg>

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

解决方案

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

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

如果你不想使用 3rd 方库,你可以用普通的 javascript 来做,但是你的 svg 字符串 应该附加到 dom 中:

var svgString = a='<svg width="612" height="394" xmlns="http://www.w3.org/2000/svg"><g><title>第 1 层</title><rect id="svg_1" height="152" width="265" y="44" x="91" stroke-width="5" stroke="#000000" fill="#FF0000"/><g><title>第 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/>

I have a String of a svg drawing. For example my string var has this content:

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

is there a easy way to get informations? for example, what is the best way to get the height of the rect? how to select only the height of the rect from the Layer 2? Thanks for the answer

解决方案

use a xml dom parser.
As stated in other answers, jQuery is a very good solution for manipulating and traversing html/xml :

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

If you don't want to use 3rd party libs, you could do this in plain javascript, but your svg string should be appended into the 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'); 

Here's a working demo : http://jsfiddle.net/gion_13/5K5x2/

这篇关于如何从javascript中的svg字符串获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆