我到处搜索这个问题的答案,找到了一些我认为可能有用的资源,但最终没有找到答案。这里有一些...
问题
我想做的是将现有的 SVG 元素或字符串附加到页面上的 DIV,然后能够在其上应用各种 D3.js 属性和特性,这样我以后就可以操作和使用它(例如如应用缩放功能等)。
我之前使用的是 jQuery SVG我在其中这样做:
var shapesRequest= '"<svg id="shapes" width="640" height="480" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg">' +
'<polygon id="svgSection_Floor" points="222.61,199.75,222.61,295.19,380.62,295.19,380.62,199.75,222.61,199.75,368.46,283.92,233.54,283.92,233.54,209.12,368.46,209.12,368.46,283.92" title="Floor" link="Primary" />' +
'<text x="302.61" y="289.4705">Floor</text>...and a lot more of the same...</svg>';
$('#svgtmp').append(shapesRequest);
$('#svgtmp #shapes text').attr('fill', 'white').attr('font-size', '9').attr('font-weight', 'bold');
$('#pnlShapes').width(640).height(480).svg().svg('get').add($('#svgtmp #shapes'));
基本上 jQuery SVG 和我的代码所做的是将 SVG 字符串附加到一个临时 DIV,操作 SVG 中的一些属性,然后将该 SVG 添加到它在页面上的永久位置。
这正是我想用 D3 做的。尽管我不确定是否需要先附加到临时 DIV,因为我可以访问 SVG 字符串并且可以使用 D3 将其附加/附加到 DOM 元素。
我试过的...
var mapSvg = d3.select("#pnlShapes").append("svg").attr("width", svgWidth).attr("height", svgHeight);
d3.xml(shapesRequest, function (xmlData) {
var svgNode = xmlData.getElementsByTagName("svg")[0];
mapSvg.node().appendChild(svgNode);
});
但这不是正确的方法,因为我没有点击外部 API 端点来检索 SVG - 我已经将它存储为字符串。
我也在考虑做这样的事情
d3.select("#pnlShapes").append('svg').append(shapesRequest).attr("width", svgWidth).attr("height", svgHeight);
但是 .append()
在使用 D3 时不用于这种追加。
问题
使用 D3 将现有 SVG 字符串附加到 DOM 的正确方法是什么(如果有帮助,我也在使用 jQuery)? 我的最终目标是附加此 SVG,然后使用 this tutorial 使其可缩放作为我的基地。
最佳答案
您可以使用 .html
将字符串插入 DOM 节点
d3.select('#svgtmp').append('div').html('<svg...')
没有 <div>
可能会有更优雅的方式.
关于javascript - D3 将现有的 SVG 字符串(或元素)追加(插入)到 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29855452/