首页 > 解决方案 > 使用 mouseover 和 mouseout 时如何在多个折线图中显示每个变量名称?(d3.js)

问题描述

我想在鼠标悬停该行时显示每个变量名称,它是文本,我使用 mouseover 和 mouseout 方法来触发它,但它没有在折线图上显示任何作为变量名称的文本,而且它也不会弹出在控制台上显示任何错误消息。

 var margin = {top: 10, right: 80, bottom: 30, left: 60},
      width = 960 - margin.left - margin.right,
     height = 600 - margin.top - margin.bottom; 

 svg.selectAll(".line")
    .data(sumstat)
    .enter()
    .append("path")
    .attr("fill", "none")
    .attr("stroke", function(d){ return color(d.key) })
    .attr("stroke-width", 1.5)
    .attr("d", function(d){
      return d3.line()
        .x(function(d) { return x(d.Year); })
        .y(function(d) { return y(+d.Price); })
        (d.values)
        })
    .on("mouseover", function(d, i) {
          svg.append("text")
            .attr("class", "title-text")
            .style("fill", function(d){ return color(d.key) })  //it will return the different colors based on different variable names   
            .text(d.key) //it will return the different variable names   
            .attr("text-anchor", "middle")
            .attr("x", (width-margin)/2)
            .attr("y", 5);
        })
    .on("mouseout", function(d) {
          svg.select(".title-text").remove();
        })

我希望变量名称,例如作为文本的城市名称,当我使用鼠标悬停这条线时会显示在折线图上,如果鼠标移动到同一折线图中的另一条线,那么它将显示当前变量前一个变量名的名称将消失。因此,我认为在这种情况下它可能可以使用“mouseover”和“mouseout”方法,但是现在当鼠标悬停每一行时它不能显示任何内容并且也不会弹出任何错误消息。

标签: javascriptd3.jssvg

解决方案


推荐阅读