3d.js(力)-获取工具提示链接上的当前鼠标位置

3d.js (Force) - get current mouse position on the link for the tooltip

本文关键字:位置 鼠标 链接 工具提示 js 获取 3d      更新时间:2023-09-26

当鼠标在线上时,我正在尝试启用工具提示。这是我目前的设置:

HTML:

<div id="graphContainer"></div>
<div id='hoveringTooltip' style='position:fixed;'></div>

3d.js代码-基本设置:

var width = 1200,
height = 900;
var svg = d3.select("#graphContainer").append("svg")
.attr("width", width)
.attr("height", height);
 var force = d3.layout.force()
.charge(-120)
.linkDistance(80)
.size([width, height]);
//Create all the line svgs but without locations yet
var link = svg.selectAll(".link")
    .data(graph.links)
    .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", function (link) {
        return link.thick
    })
    .attr("data-info", function (link) {
        return link.info;
    })
    .style("marker-end", "url(#suit)")
    .on("mouseover", mouseOverLink)

function mouseOverLink (e) {
//d3.select(this).style("stroke","red");
d3.select(this).attr("class", "link_selected");
 var that = this;
var value = Number( this.attributes.x1.value );
var xx = d3.select(this).attr("cx") + "px"
var yy = d3.select(this).attr("cy") + "px"
var xxx = d3.event.pageX;
var yyy =     d3.event.pageY;
var coordinates = [0, 0];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];

var value = this.attributes[1].value;
$('#hoveringTooltip').show();
$('#hoveringTooltip').html(value);
$('#hoveringTooltip').css({
    "top": xxx,
    "left": yyy
});
 }

在mouseOverLink功能中,我已经尝试了在SO和互联网上可以找到的所有场景。我确实得到了X/Y鼠标的值,但它们总是错误的。我还尝试使用Jquery事件来附加mouseover链接,但这些值也是错误的。

如果有其他方法可以在链接上显示toolitip,我会非常高兴。

由于您没有提供工作小提琴,所以我制作了一个力导向Plunk来解释解决方案。

首先给出工具提示div的样式,如下所示:

div.tooltip {
    position: absolute;// because we are going to give the position.
    text-align: center;
    width: 160px;
    height: 50px;
    padding: 2px;
    font: 12px sans-serif;
    background: lightsteelblue;
    border: 0px;
    border-radius: 8px;
    pointer-events: none;
}

接下来制作一个div并将其附加到正文中,如下所示:

var tooltip = d3.select("body").append("div")
        .attr("class", "tooltip")
        .style("opacity", 0);//so that its not visible initially

现在链接鼠标悬停/鼠标退出进行

  var link = svg.selectAll(".link")
      .data(graph.links)
    .enter().append("line")
      .attr("class", "link")
      .on("mouseover", function (d, i) {//show tooltip
        tooltip.transition()
            .duration(200)
            .style("opacity", 0.9);
            tooltip.html("<p>source:"+d.source.name+ "</p><p>target:"+d.target.name+ "</p>")//tool tip html
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
      })
      .on("mouseout", function (d) {
            tooltip.transition()
            .duration(500)
            .style("opacity", 0);//hde tooltip
          })

这里的工作示例。

将鼠标悬停在链接上可查看工具提示。

我的第一个想法是,如果您在css样式规则中使用xxx和yyy,则需要像对xx和yy 所做的那样,在值的末尾添加"px"