仅复制字符串中svg的子元素

时间:2014-06-02 11:21:37

标签: javascript jquery svg

我有一个像这样的动态svg:

<svg xmlns="http://www.w3.org/2000/svg" id="mysvg" style="cursor: crosshair; width: 1792px; height: 1280px;">
<line id="2014_5_5_14_30_37_Line" x1="100.44444444444444" y1="190.14814814814815" x2="235.55555555555554" y2="429.55555555555554" stroke-width="5" stroke="#00ff00" opacity="1.0" Username="UserName" CurrentDate="30/05/2014" stroke-opacity="1" style="cursor: move;"/>
<polyline id="2014_5_5_14_30_38_polyline" stroke-width="5" stroke="#00ff00" opacity="1" Username="UserName" CurrentDate="30/05/2014" points="268.74074074074076,199.62962962962962,493.9259259259259,164.07407407407408,605.3333333333334,289.7037037037037,548.4444444444445,408.22222222222223,368.2962962962963,334.74074074074076,368.2962962962963,334.74074074074076" stroke-opacity="1" style="fill: none; cursor: move;"/>
<g id="2014_5_5_14_30_43_gRect">
<rect Username="UserName" CurrentDate="30/05/2014" x="866.074074074074" y="164.07407407407408" id="2014_5_5_14_30_43_Rect" width="270.2222222222223" height="168.2962962962963" fill="#FFF" stroke-width="5" stroke="#00ff00" fill-opacity="0.3" style="fill: rgb(255, 255, 255); cursor: move;"/>
<foreignObject x="866.074074074074" y="164.07407407407408" width="270.2222222222223" height="168.2962962962963" id="2014_5_5_14_30_43_Rect_f">
<div xmlns="http://www.w3.org/1999/xhtml" color="black" style="font-family: arial; font-size: 20px; font-style: normal; text-align: center; vertical-align: middle;">some text
</div>
</foreignObject>
</g>
</svg> 

我希望通过javascript或Jquery函数将<svg> and </svg>标记内的所有内容都包含在字符串中。

现在我正在这样做:

var svg = document.getElementById('mysvg');
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);
alert(str);

但是这会输出整个svg元素,即来自&#34; <svg...</svg>&#34;。我希望输出为&#34; <line....</g>&#34;在这种情况下。我尝试过使用svg.getElementsByTagName('*'),但我似乎无法获得我想要的输出。

在JQuery或javascript中是否有类似innerSVG的内容?

2 个答案:

答案 0 :(得分:2)

function svgInnerHTML (svg) {
  // Chrome, Firefox, etc.
  if (svg.innerHTML) {
    return svg.innerHTML;
  }

  // Safari case
  var serializer = new XMLSerializer();
  var str = '';
  var children = svg.childNodes;

  for (var i = 0, len = children.length; i < len; i += 1) {
    str += serializer.serializeToString(children[i]);
  }

  return str;
}

答案 1 :(得分:1)

你为什么不用:

var svg = document.getElementById('mysvg');
alert(svg.innerHTML);

看到这个小提琴:

http://fiddle.jshell.net/Um5yf/