d3-鼠标悬停时的工具提示定位

时间:2019-06-14 12:17:39

标签: d3.js

我有一个演示here

我有一个d3堆叠面积图。

当我将鼠标悬停在图表上时,将显示该图表那部分的工具提示宽度数据。

我的问题是工具提示中的位置。

我可以设置y位置,但我希望x位置位于鼠标悬停的突出显示区域的中央。

我可以得到鼠标悬停区域的xpos和宽度,但是工具提示似乎与之偏离了中心。

const ttLayer = this.chart.append('g')
      .classed('tooltip-layer', true)

    ttLayer.selectAll('rect')  
      .data(data[0])
      .enter()
      .append('rect')
      .classed('tooltip-rect', true)
      .attr('height', this.height)
      .attr('width', this.x.bandwidth())
      .attr('x', (d) => this.x(d.data.date))
      .on('mouseover', function(d, i){

        const block = d3.select(this)
        block.style('opacity', .1)

        const centerLine = +block.attr('x') + +block.attr('width')/2

        let html = 
          `<div>
            <p>${d.data.date}</p>
            <p>${d.data.one}</p>
            <p>${d.data.two}</p>
            <p>${d.data.three}</p>
          <div>`

        const tooltip = d3.select('.chart-tooltip');
        const svg = d3.select('#chart-svg');

        tooltip.style("display", null);

        tooltip
          .style("left", centerLine + 'px')
          .style("top", 40 + "px")
          .html(html)
      })

      .on('mouseout', function(){
        d3.select(this).style('opacity', 0)
        const tooltip = d3.select('.chart-tooltip');
        tooltip.style("display", 'none');
      });

0 个答案:

没有答案