【问题标题】:How to add popup on D3.js visualization (tree nodes)如何在 D3.js 可视化(树节点)上添加弹出窗口
【发布时间】:2023-01-25 04:21:46
【问题描述】:

我们正在使用 d3.js 树 (d3.tree()) 来呈现组织结构图可视化。它非常类似于 https://observablehq.com/@julienreszka/d3-v5-org-chart

我想在单击/鼠标悬停某个按钮时在节点上显示小弹出窗口。例如单击人像会显示带有更多操作的小弹出窗口。因此用户可以单击弹出窗口中的任何链接。

有什么推荐的方法可以在 D3js 中实现它吗?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您可以在更新节点时附加事件侦听器以进行单击或鼠标悬停。就像你提到的例子有这段代码:

    // Updating nodes
    const nodesSelection = centerG.selectAll('g.node')
      .data(nodes, d => d.id)
    
    // Enter any new nodes at the parent's previous position.
    var nodeEnter = nodesSelection.enter().append('g')
      .attr('class', 'node')
      .attr("transform", function(d) {
        return "translate(" + source.x0 + "," + source.y0 + ")";
      })
      .attr('cursor', 'pointer')
      .on('click', function(d) {
        if ([...d3.event.srcElement.classList].includes('node-button-circle')) {
          return;
        }
        attrs.onNodeClick(d.data.nodeId);
      })
    

    如果您在此处选中 onclick,它正在调用 NodeClick 方法,您将需要更改 NodeClick,或者如果您想要 mouseover 方法,请添加 .on('mouseover') 事件。如果你想在节点中定位图像然后在这个地方添加事件

    nodeUpdate.selectAll('.node-image-group')
      .attr('transform', d => {
        let x = -d.imageWidth / 2 - d.width / 2;
        let y = -d.imageHeight / 2 - d.height / 2;
        return `translate(${x},${y})`
      })
    
    
    nodeUpdate.select('.node-image-rect')
      .attr('fill', d => `url(#${d.id})`)
      .attr('width', d => d.imageWidth)
      .attr('height', d => d.imageHeight)
      .attr('stroke', d => d.imageBorderColor)
      .attr('stroke-width', d => d.imageBorderWidth)
      .attr('rx', d => d.imageRx)
      .attr('y', d => d.imageCenterTopDistance)
      .attr('x', d => d.imageCenterLeftDistance)
      .attr('filter', d => d.dropShadowId)
    

    【讨论】:

    • 谢谢你的回答!我了解在组织结构图节点内的 btns 上添加事件侦听器的实现。除此之外,我想要的是显示带有更多选项/链接的弹出窗口/模式。当我们在节点内的特定区域(btn/image)上单击/鼠标悬停时,每个节点都会显示弹出窗口。弹出窗口将与每个节点相邻。我没有找到在 D3js 可视化上显示弹出窗口的任何方法。
    • 您可以在 d3 上使用工具提示。那里有很多示例。工具提示只是一种弹出窗口,可以分配更大的宽度和高度,例如observablehq.com/@benoldenburg/patterns-tooltip
    【解决方案2】:

    试试 Tippy,效果很好。请以https://dev.to/plebras/d3-tippy-easy-tooltips-on-your-visualisations-59l3 为起点。

    【讨论】:

    • Kneup 向导,请不要只发布一些工具或库作为答案。至少在答案本身中展示how it solves the problem
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多