在我的D3图表中,mousemove和mouseover对于所附图片中描述的最后一个数据不起作用。
它总是将工具提示显示到倒数第二个元素。我也有最后一个元素的数据,但它只显示鼠标移动和鼠标悬停在图表中的倒数第二个元素(线和圆)。

数据-
var data = [
{
startTime: "1567765320049",
magnitude: 0
},
{
startTime: "1567851720049",
magnitude: 0
},
{
startTime: "1568024520049",
magnitude: 10
},
{
startTime: "1568283720049",
magnitude: 10
},
{
startTime: "1568629320049",
magnitude: 0
},
{
startTime: "1569061320049",
magnitude: 0
},
{
startTime: "1569579720049",
magnitude: -20
},
{
startTime: "1570184520049",
magnitude: -20
},
{
startTime: "1570875720049",
magnitude: 0
},
{
startTime: "1571653320049",
magnitude: 10
},
{
startTime: "1572517320049",
magnitude: 0
},
{
startTime: "1573467720049",
magnitude: 0
},
{
startTime: "1574504520049",
magnitude: 10
},
{
startTime: "1575627720049",
magnitude: 10
}
];我在这里有一个有效的代码沙箱-
https://codesandbox.io/s/sad-bell-qqwwe
谢谢。
发布于 2019-09-09 14:25:25
这就是我修复这个问题的方法,我正在获取哪个日期值最接近鼠标并显示在工具提示中。
.on("mouseover", function(d) {
focus.style("display", null);
div
.transition()
.duration(200)
.style("opacity", 0.9);
})
.on("mouseout", function() {
focus.style("display", "none");
div
.transition()
.duration(300)
.style("opacity", 0);
})
.on("mousemove", function() {
var mouse = d3.mouse(this);
var mouseDate = xScale.invert(mouse[0]);
var i = bisectDate(data, mouseDate); // returns the index to the current data item
var d0 = data[i - 1];
var d1 = data[i];
let d;
// work out which date value is closest to the mouse
if (typeof d1 !== "undefined") {
d = mouseDate - d0.startTime > d1.startTime - mouseDate ? d1 : d0;
} else {
d = d0;
}
div
.html(
`<span>${parseDate(d.startTime)}</span>
<span>Magnitude: ${d.magnitude} </span>`
)
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY - 28 + "px");
var x = xScale(d.startTime);
var y = yScale(d.magnitude);发布于 2019-09-09 15:03:04
您可以将覆盖矩形width/2向左移动:
g.selectAll("dot")
.data(data)
.enter()
.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.attr("x", (d) => xScale(d.startTime) - width/2) //<<<<< new line
.on("mouseover", function(d) {
focus.style("display", null);
divhttps://stackoverflow.com/questions/57799739
复制相似问题