【问题标题】:Tooltip is not displaying despite data being present尽管存在数据,但工具提示未显示
【发布时间】:2019-03-04 10:21:18
【问题描述】:

我有这个 d3 项目,我在其中创建了条形图。我有几个栏,我希望将鼠标悬停在特定栏上时显示数据。但是,由于某种原因,尽管存在数据和 css,但它不会显示内容。我将 rects 元素创建为条形图和一个带有包含数据的工具提示类的 div 元素。请帮忙。

这是我的代码:

  chart.selectAll("rect")
    .data(json.data)
    .enter()
    .append("rect")
    .attr("x", (d) => xScale(parseDate(formatDate(d[0]))))
    .attr("y", (d) => yScale(d[1]))
    .attr("height", (d) => height - yScale(d[1]))
    .attr("width", xScale.bandwidth())
    .attr("class", "rect-col")

    .append("div")
    .attr("class", "tooltip")
    .text((d) => d[0] + d[1])
    .on("mouseenter", function (d, i) {
      //d3.select(this).style("fill", "#EE9A2F");
      d3.select(this).style("visibility", "visible");


    })
    .on("mouseleave", function (d, i) {
      //d3.select(this).style("fill", "#EECF10");
      d3.select(this).style("visibility", "visible");
    });

我的 CSS:

.tooltip {           
  text-align: center;           
  width: 60px;                  
  height: 28px;                 
  padding: 2px;             
  font: 12px sans-serif;        
  background: green;   
  border: 0px;      
  border-radius: 8px;           
  pointer-events: none;    
  color: red;
  visibility: hidden;

}

链接到我的代码笔 codepen

【问题讨论】:

    标签: javascript d3.js svg tooltip


    【解决方案1】:

    简而言之:您不能<div> 附加到 SVG <rect>

    这里的解决方案是为 div 创建一个选择...

    const tooltip = d3.select("body")
        .append("div")
        .attr("class", "tooltip");
    

    ...然后,在矩形的"mouseenter" 侦听器内:

    tooltip.style("visibility", "visible")
        .text(d[0] + d[1])
    

    这是您更新后的 CodePen,您将在图表下方看到工具提示:https://codepen.io/anon/pen/LaZgvp?editors=0010。这可能会引出您的下一个问题:“如何将工具提示放置在相应矩形的上方/旁边?” 这个问题的答案,当然是重复的,可以通过简单的搜索找到(例如:https://stackoverflow.com/a/41625629/5768908https://stackoverflow.com/a/40720100/5768908)。

    【讨论】:

    • 正确。我不知道您不能将 div 附加到 rect。谢谢 Gerardo,是的,我想问如何将它放在正确的矩形上。再次感谢您:)祝您有美好的一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多