将D3工具提示放置在光标位置

Placing D3 tooltip in cursor location

本文关键字:光标 位置 D3 工具提示      更新时间:2023-09-26

我在我的可视化中使用3d -tip。现在,我想将工具提示添加到非常宽的元素中,这些元素可能会延伸到可见画布之外。默认情况下,工具提示显示在对象的水平中心,这意味着在我的情况下,工具提示可能不在可见区域。我需要的是工具提示显示在光标的水平位置,但我不知道如何正确地改变工具提示的位置。我可以设置偏移量,也可以获得光标的坐标,但我无法获得工具提示的初始位置,因此我无法计算正确的偏移量。也不能设置绝对位置:

            .on("mouseover",function(d){
                var coordinates = [0, 0];
                coordinates = d3.mouse(this);
                var x = coordinates[0];
                var y = coordinates[1];
                tip.offset([-20,20]); // this works
                tip.attr("x",40); // this doesn't
                tip.show(d);
            })

如果想使用偏移量,可以在tip.show(d):

之后获取工具提示的初始位置。
tip.style('top');
tip.style('left');

同样,要设置绝对位置:

.on('mouseover', function(d){
        var x = d3.event.x,
            y = d3.event.y;
        tip.show(d);
        tip.style('top', y);
        tip.style('left', x);
      })

前面说的答案不适合我(,不能修改为"建议编辑队列已满…"),但经过一些小的调整,它工作得很好:

.on('mouseover', function(d){
    var x = d3.event.x,
        y = d3.event.y;
    tip.show(d);
    tip.style('top', y-10 + 'px'); // edited
    tip.style('left', x+'px'); // edited
  })