【发布时间】:2015-07-02 07:37:16
【问题描述】:
我已经在 d3 中实现了我认为相对简单的鼠标悬停行为,但我显然遗漏了一些东西,因为我似乎无法弄清楚它为什么不起作用。
目标是让文本块与数据点数组关联,并在用户将鼠标悬停在数据点上时显示文本块。当用户点击数据点时,文本块仍然可见。我没有使用工具提示,因为我需要一次显示多个文本块。
首先,我使用 Bostock 本人 (http://bl.ocks.org/mbostock/7555321) 的包装函数在 svg 中创建文本块
function wrap(text, width, xLoc, yLoc) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.0, // ems
y = text.attr("y"),
//dy = parseFloat(text.attr("dy")),
dy = 0,
tspan = text.text(null).append("tspan").attr("x", xLoc).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", xLoc).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
块本身是使用这个函数创建的:
svgContainer.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", function(d) { return d.x_axis; })
.attr("y", function(d) { return d.y_axis; })
.attr("id", function(d) {return("textBlock" + d.documentNumber);})
.attr("visibility", "visible")
.text(function(d) { return d.description;});
.call(wrap, 200, function(d) { return d.x_axis; }, function(d) { return d.y_axis; });
数据点的鼠标悬停功能(绘制为 svg 圆圈)如下所示。请注意,以下配置仅用于打开#textBlock5 的可见性,而不管鼠标悬停在哪个圆圈上;这是一个调试步骤,只是为了从 select 语句中删除函数
svgContainer.selectAll("circle")
.data(data)
.on("mouseover", function(d){
return console.log("#textBlock"+d.documentNumber);
d3.select("#textBlock5").attr("visibility", "visible");
});
在 DOM 中正确构造了 id(见下文),但是 mouseover 函数并没有改变可见性属性...谁能帮我找出我做错了什么!?
<text x="927.1563942727792" y="673.2598605856803" id="textBlock5" visibility="visible">
<tspan x="927.1563942727792" y="673.2598605856803" dy="0em">text here</tspan>
//more tspans here...
</text>
【问题讨论】:
-
是
__return__ console.log("#textBlock"+d.documentNumber);的目的吗?现在,鼠标悬停处理程序永远不会到达可见性更改线。 -
你的小提琴在哪里?
标签: javascript css d3.js