首页 > 解决方案 > d3.JS 工具提示不会像预期的那样在鼠标移出时隐藏,而是在鼠标悬停时复制而不是移动

问题描述

我正在处理带有圆圈和回归线的 d3.js 散点图。对于两者,我希望用户能够将鼠标悬停在它们上并查看它们的值。不幸的是,我的工具提示没有按预期运行。

当我将鼠标放在一个圆圈或回归路径上时,我看不到一个工具提示,我看到两个工具提示。一个在我页面的左上角,第二个是我将鼠标悬停在元素上的位置。

当我将鼠标移出一个元素时,刚刚创建的两个工具提示不会按预期“消失”(将样式更改为隐藏)。谁能让我知道我在这里做错了什么?我已经包含了工具提示、鼠标悬停、鼠标悬停、handleMouseOut 和handleMouseOver 的代码。

    const tip =d3.select("body")
        .append("div")
        .attr("class","card")
        .style("padding", "8px")
        .style("position", "absolute")
        .style("left", 0)
        .style("top", 0)
        .style("visibility", "hidden");

        svg.selectAll('circle')
            .on("mouseover", (e, d) => {
                let content = `<div class='tooltip-label'>
                 ${filter_one.org}-${filter_one.type}: ${d[filter_one.org][filter_one.type]} <br/>
                 ${filter_two.org}-${filter_two.type}: ${d[filter_two.org][filter_two.type]}
                </div>`;
                tip.html(content).style("visibility", "visible")
                handleMouseOver(e, d)
            }).on("mouseout", (e, d) => {
                tip.style("visibility", "hidden");
                handleMouseOut(e, d);
              })
              .on("mousemove", (e, d) => {
                tip.style("transform", `translate(${e.pageX}px,${e.pageY}px)`);
              });
            
              svg.selectAll('path')
              .on("mouseover", (e, d) => {
                  let x_value = Math.round(xScale.invert(e.pageX)-(spacing*2));
                  let y_value = Math.round(linearRegressionLine(x_value));
                  let content = `<div class='tooltip-label'>
                  ${filter_one.org}-${filter_one.type}: ${x_value}
                <br/>
                ${filter_two.org}-${filter_two.type}: ${y_value}
                  </div>`;
                  tip.html(content).style("visibility", "visible")
                  console.log(d)
                  handleMouseOver(e, d)
              }).on("mouseout", (e, d) => {
                  tip.style("visibility", "hidden");
                  handleMouseOut(e, d);
                })
                .on("mousemove", (e, d) => {
                  tip.style("transform", `translate(${e.pageX}px,${e.pageY}px)`);
                });
              
    
        const handleMouseOver = (e, d) =>{
            d3.select(e.currentTarget)
              .transition()
              .duration(200)
              .attr("fill", "#334040");
        }
      
         const handleMouseOut = (e, d) => {
        d3.select(e.currentTarget)
          .transition()
          .duration(300)
          .attr("fill", "#5FA19E");
      };

标签: d3.js

解决方案


推荐阅读