D3.js: Position tooltips using element position, not mouse position?

后端 未结 4 897
滥情空心
滥情空心 2020-12-02 17:13

I\'m using D3 to draw a scatter graph. I would like to show tooltips when the user mouses over each circle.

My problem is that I can append tooltips, but they\'re p

4条回答
  •  春和景丽
    2020-12-02 17:32

    In my experience, the easist solution is as follows:

    First, getBoundingClientRect() to get the position of your element.

    Then, use window.pageYOffset to adjust the height, relative to where you are.

    E.g.

    .on('mouseover', function(d) {
        let pos = d3.select(this).node().getBoundingClientRect();
        d3.select('#tooltip')
            .style('left', `${pos['x']}px`)
            .style('top', `${(window.pageYOffset  + pos['y'] - 100)}px`);
    })
    

    In the example above, I don't use X's offset because we rarely need to (unless you're scrolling horizontally).

    Adding window.pageYOffset and pos['y'] gives us the current mouse position (wherever we are on the page). I subtract 100 to place the tooltip a little above it.

提交回复
热议问题