gpt4 book ai didi

javascript - 单击数据标签时添加输入文本框 d3.js

转载 作者:行者123 更新时间:2023-11-29 23:31:00 25 4
gpt4 key购买 nike

我正在尝试使用 d3.js v3 在我的散点图上实现注释。我想在单击图表上的文本标签时插入一个文本框。我为此编写了这段代码:

circleGroup.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function (d) {
if (d.label) {
return d.label;
}
return "";
})
.attr("x", function (d) {
return x(d.time) + 6;
})
.attr("y", function (d) {
return y(d.plotY) + 4;
})
.attr("font-size", "10px")
.attr("fill", "#2d3d45")
.on("click", function(d) {
d3.select(this).append("input").attr("type", "text").attr("name", "textInput").attr("value", "Text goes here");

});

文本元素的选择工作正常。当我单击文本标签时,它只是不弹出文本框。我哪里错了?我的方法方向不对吗?

最佳答案

您不能将 html 元素附加到 svg 中。唯一的方法 - 使用 foreignObject元素。

The foreignObject SVG element allows for inclusion of a foreign XML namespace which has its graphical content drawn by a different user agent. The included foreign graphical content is subject to SVG transformations and compositing.

看一个非常简单的例子:

var texts = ['foo', 'bar'];

var container = d3.select('g');

container
.selectAll('text')
.data(texts)
.enter()
.append('text')
.text(function(d) { return d; })
.attr('y', function(d,i) { return 50 * i })
.on('click', function(d,i) {
container
.append("foreignObject")
.attr("x", 0)
.attr("y", function() { return 50 * i })
.attr("width", 140)
.attr("height", 20)
.html(function(d) {
return '<input type="text" value="Text goes here" />'
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div style="font-size: 12px;">Click on the texts below:</div>
<svg width="300" heigth="400">
<g transform="translate(20, 20)">
</g>
</svg>

关于javascript - 单击数据标签时添加输入文本框 d3.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404688/

25 4 0