项目
我使用 <use ...></use>
在我的项目中包含一个 SVG如下:
<use xlink:href="myMap.svg#status-map"></use>
在浏览器中检查时会产生:
<svg id="status-map" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1247.244px" height="907.087px" viewBox="64.094 122.25 985.889 657.072" enable-background="new 0 0 1247.244 907.087" xml:space="preserve">
<g id="road">...</g>
<g id="river">...</g>
<g id="station">...</g>
etc etc etc
</svg>
问题
我需要做的就是对内部<g></g>
进行分组元素,因此代码变为:
<svg id="status-map" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1247.244px" height="907.087px" viewBox="64.094 122.25 985.889 657.072" enable-background="new 0 0 1247.244 907.087" xml:space="preserve">
<g id="container"> // <-- new container
<g id="road">...</g>
<g id="river">...</g>
<g id="station">...</g>
etc etc etc
</g>
</svg>
我尝试使用 innerHTML
提取并包装它但这对于 SVG 文件/代码会失败。
也尝试过
我还尝试简单地输入 <use>
在 <g>
元素,但这也不起作用。
我需要这样做的原因是我正在使用 SVGPAN允许我放大和缩小,并拖动...这需要内部 <g>
要包裹在外部的元素
有办法做到这一点吗?
最佳答案
您可以使用 JS 操作 svg 的 DOM:
var svg = document.getElementById("svg");
var svgNS = svg.namespaceURI;
var e = document.createElementNS(svgNS, 'g');
e.setAttribute('id', 'container');
while(svg.firstChild) {
e.appendChild(svg.firstChild);
}
svg.appendChild(e);
关于javascript - SVG 使用 - 添加到组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962240/