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

时间:2016-01-13 11:20:30

标签: javascript jquery d3.js

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

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和Internet上找到的场景。我确实得到了X / Y鼠标的值,但它们总是错误的。我还尝试使用Jquery事件附加鼠标悬停链接,但这些值也是错误的。

如果有其他方式在链接上显示工具提示,我会更高兴。

2 个答案:

答案 0 :(得分:2)

由于你没有提供一个工作小提琴,所以我做了一个强制导向的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
          })

工作示例here

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

答案 1 :(得分:0)

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