【发布时间】:2019-12-05 20:10:01
【问题描述】:
每当单击文本元素时,我都会调用以下函数。一旦被调用,它会通过 id 选择一个元素,然后将其不透明度更改为 0 或 1。
d3.select("#viz").selectAll("text").on("click", function() {
selectedCandidate = d3.select(this).attr("id").split(",")[0];
selectedColor = d3.select(this).attr("id").split(",")[1];
// determine if the line with same id as the text is visible
var active = document.getElementById(selectedCandidate).active ? false : true,
newOpacity = active ? 0 : 1;
newColor = active ? "gray" : selectedColor;
// hide or show the elements
d3.selectAll("#"+selectedCandidate)
.style("opacity", newOpacity);
})
这完全符合预期。我现在想添加一个过渡,所以不透明度的变化是渐进的。我希望解决方案看起来像这样:
// hide or show the elements
d3.select("#"+selectedCandidate)
.transition()
.duration(3000)
.style("opacity", newOpacity);
这在控制台中按预期工作,但在函数内部,它完全停止工作。相反,当函数被调用时,不透明度会停止变化。
【问题讨论】:
-
我在下面发布了一个工作示例,但可能无法完全理解您的问题。我要注意的一件事是使用
selectAll按ID 选择元素。 Each element in your HTML document should have a unique ID。如果您确实有多个具有相同 ID 的元素,我建议改用类(或其他属性)。 -
我只是将其更改为“select”而不是“selectAll”,因为所有内容确实都有唯一的 ID。不幸的是,过渡仍然没有奏效。
标签: function d3.js transition duration