看到这里的变化:
https://jsfiddle.net/fk6gfwjr/1/
基本上需要通过y位置进行排序的提示,然后我们做出那种为了确保周边提示通过的最小距离是分开的(我捡15像素) 。然后将以前计算的y位置的偏移量添加到工具提示文本。我还给文字加上了颜色,让他们更容易辨别哪个是哪个。
var ypos = [];
d3.selectAll(".mouse-per-line")
.attr("transform", function(d, i) {
// same code as before
// ...
// add position to an array
ypos.push ({ind: i, y: pos.y, off: 0});
return "translate(" + mouse[0] + "," + pos.y +")";
})
// sort this array by y positions, and make sure each is at least 15 pixels separated
// from the last, calculate an offset from their current y value,
// then resort by index
.call(function(sel) {
ypos.sort (function(a,b) { return a.y - b.y; });
ypos.forEach (function(p,i) {
if (i > 0) {
var last = ypos[i-1].y;
ypos[i].off = Math.max (0, (last + 15) - ypos[i].y);
ypos[i].y += ypos[i].off;
}
})
ypos.sort (function(a,b) { return a.ind - b.ind; });
})
// Use the offset to move the tip text from it's g element
// don't want to move the circle too
.select("text")
.attr("transform", function(d,i) {
return "translate (10,"+(3+ypos[i].off)+")";
}
;