【问题标题】:D3 transition/duration not working inside functionD3 过渡/持续时间在函数内部不起作用
【发布时间】: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


【解决方案1】:

我们无法完全测试您的代码,因为我们不知道您的svg 中的text 元素的结构。

我认为它停止工作是因为您可能没有更新 active 属性?

this 这样的东西怎么样?我创建了一个类似的场景,它似乎可以满足您的需求。

所以有了这个 HTML:

<body>
  <div class="container">
    <div>
      <svg id="viz" width="500" height="500">
        <text id="text1" x="10" y="20" active="0" >Text 1</text>
        <text id="text2" x="10" y="50" active="0" >Text 2</text>
        <text id="text3" x="10" y="80" active="0" >Text 3</text>
      </svg>
    </div>
  </div>
</body>

你的点击功能是这样工作的:

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 = d3.select("#"+selectedCandidate).attr('active') === "0" ? true : false;

  newOpacity = active ? 0 : 1;
  newActive = active ? 1 : 0;

  // hide or show the elements
  d3.select("#"+selectedCandidate)
    .attr("active", newActive)
    .transition()
    .duration(500)
    .style("opacity", newOpacity);
})

应该足以切换文本不透明度。

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 2017-01-12
    • 1970-01-01
    • 2018-10-20
    • 2020-07-02
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多