我注意到,当我将 DOM/SVG 元素附加到现有对象内联时,以及在使用 D3 javascript 库时的单独步骤中时,我得到了混合的结果。如果我查看引用原始 SVG 对象的变量,它会在创建原始对象期间附加另一个对象时发生变化。这是一个例子:
var body = d3.select("body");
var svg = body.append("svg")
.attr("width", '100%')
.attr("height", '100%')
var html1 = svg.append("foreignObject")
.attr("x", 50)
.attr("y", 25)
.attr("width", 200)
.attr("height", 100)
.attr('id', 'fo1')
.append("xhtml:div")
.html("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam.");
var html2 = svg.append("foreignObject")
.attr("x", 250)
.attr("y", 25)
.attr("width", 200)
.attr("height", 100)
.attr('id', 'fo2');
html2.append("xhtml:div")
.html("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam.");
console.log('first fo:', html1[0]);
console.log('first fo id:', d3.select('#fo1')[0]);
console.log('second fo:', html2[0]);
输出看起来像:
first fo:
Array[1]
0: div
length: 1
parentNode: html
__proto__: Array[0]
first fo id:
Array[1]
0: foreignobject#fo1.[object SVGAnimatedString]
length: 1
parentNode: html
__proto__: Array[0]
second fo:
Array[1]
0: foreignobject#fo2.[object SVGAnimatedString]
length: 1
parentNode: html
__proto__: Array[0]
在创建过程中将 DIV 元素内联附加到 foreignObject 元素后,变量从foreignObject更改为div。在额外的步骤中执行此操作不会改变参考。这是相应的 jsfiddle 有人可以向我解释一下并告诉我如何避免它吗?