【问题标题】:D3.select(this) but filterD3.select(this) 但过滤
【发布时间】:2021-01-07 13:04:38
【问题描述】:

我正在研究 D3 强制图并遇到了挑战。我添加了一个“mouseenter”功能,如果悬停,它会增加节点的半径。

.on("mouseenter", function(d) {
                    d3.select(this)
                        .transition()
                        .duration(200)
                        .attr("r", 50)

现在我想排除某些节点并认为过滤会有所帮助。不幸的是,它没有。可能我的代码是错误的,或者我需要稍后添加这些过滤。有什么想法吗?

 .on("mouseenter", function(d) {
                    d3.select(this)
                        .filter(function() {
                            return !this.graph.nodes.name("usv"))
                        })
                        .transition()
                        .duration(200)
                        .attr("r", 50)

最好的,

克里斯蒂安

【问题讨论】:

  • .on 之前应用.filter,以便事件处理程序仅附加到感兴趣的事件处理程序。而且我不确定this.graph.nodes.name 位是功能代码。
  • 嗨@Mark 感谢您的快速回复。不幸的是,它没有成功。如果我在显示非节点的“mouseenter”功能之前应用过滤器。即使我以某些方式更改过滤器。

标签: javascript jquery d3.js


【解决方案1】:

这是一个示例实现:

<!doctype html>

<html>
  <head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <svg width="500" height="500"></svg>
    <script>
      let data = d3.range(10)
        .map(function(d){
          return {
            name: Math.random() > 0.5 ? "usv" : "na",
            x: Math.random() * 480,
            y: Math.random() * 480
          };
        });

      d3.select('svg')
        .selectAll('circle')
        .data(data)
        .enter()
        .append('circle')
        .attr('cx', d => d.x)
        .attr('cy', d => d.y)
        .attr('r', 20)
        .attr("fill", d => d.name == "usv" ? "red" : "black")
        .filter((d) => {
          return d.name === "usv";
        })
        .on("mouseenter", function(){
          d3.select(this)
            .transition()
            .duration(200)
            .attr("r", 50);
        });
    </script>
  </body>
</html>

【讨论】:

  • 嗨@Mark 感谢您的代码。我会更新你的答案,因为它与 D3v6 配合得很好。我错过了提到我正在使用 D3v4,一旦我应用你的过滤器,就只有“usv”。我想可能问题一定出在其他地方。
  • @ICoded,我更新了我的答案以使用 d3v4,效果一样。如果您可以编写一个可运行的、可重现的问题示例,我很乐意看一看。
  • 嗨@Mark 我在您的调整的帮助下发现了我的问题。首先是语法错误,其次我试图一次修改很多。都修好了。非常感谢马克。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多