在响应式d3.js图表中添加工具提示

Adding tooltip in responsive d3.js chart

本文关键字:添加 工具提示 js 响应 d3      更新时间:2023-09-26

我正在学习使用javascript和d3.js。我用工具提示做了一个简单的线形图,效果很好(见这里)。我决定让它响应,所以使用一个模板做一个新的(见这里)。响应性是好的,但我不能添加工具提示div。任何帮助吗?

这里是有问题的代码:

    chart2.selectAll("dot")    
    .data(data)         
    .enter().append("rect")             
    .attr("width", 1)
    .attr("height", 120)      
    .style("opacity", 0)      // set the element opacity
    .style("stroke", "#6f6f6f")    // set the line colour
    .attr("xScale", function(d) { return xScale(d.date); })       
    .attr("yScale", function(d) { return yScale(d.close)-60; })   
    .on("mouseover", function(d)
     { 
     d3.select(this).attr("width", 1).style("opacity", .8)   ; //il punto cambia al mousover (bellissmo)
         div.transition()        
            .duration(70)      
            .style("opacity", .8)
            .style("border", "1px");      
        div .html(formatTime(d.date) + "<br/>"  + d.close)  
            .style("left", (d3.event.pageX) + "px")     
            .style("top", (d3.event.pageY - 64) + "px");    
        })               
    .on("mouseout", function(d) {       
       d3.select(this).attr("r", 5.1).style("opacity", .0);   
        div.transition()        
        .duration(200)      
        .style("opacity", 0);   
    });

div在这里定义:

 var div = d3.select("#chart2").append("div")   
    .attr("class", "tooltip")               
    .style("opacity", 0); 

,在CSS中为:

 div.tooltip {   
  position: absolute;           
  text-align: center;           
  width: 95px;                  
  height: 40px;                 
  padding: 2px;             
  font: 15px arial;
  font-weight: bold;
  color: black;        
 background: #f0f0f0;
  pointer-events: none;         
}

定义div如下并选择"body"并在那里添加div

var div = d3.select('body').append("div")
      .attr("id", "chart")
      .attr("class", "tooltip")
      .style("opacity", 0);