D3.js:如何在svg上移动鼠标时创建弹出事件

D3.js: How to create the pop-up event when moving mouse on the svg?

本文关键字:鼠标 移动 创建 出事件 svg js D3      更新时间:2023-09-26

每个人。我有一个问题,关于如何使用"鼠标"事件返回data.value。下面的代码可以获得当前的X位置(显示在上),而我不知道如何返回obj.value.

我已经检查了干旱作物使用的方法,但仍然坚持使用

有人能给我一些想法吗?我想你们中的一些人遇到过这种情况。

灵感来自mbostock创建的可缩放区域和可缩放贴图平铺。(将以下代码添加到可缩放区域进行调试)

<style>
.info {
  position: absolute;
  top: 100px;
  left: 50px;
}
</style>
<script>     
svg.append("rect")
    .attr("class", "pane")
    .attr("width", width)
    .attr("height", height)
    .call(zoom)
    .on("mousemove", mousemoved);
var info = svg.append("text").attr("class","info");
function mousemoved() {
//work with the x position returned, but no idea how to return the d.value
  info.text(d3.mouse(this));
}
</script>

http://bl.ocks.org/mbostock/3902569

 function mousemove() {
    var x0 = x.invert(d3.mouse(this)[0]),
        i = bisectDate(data, x0, 1),
        d0 = data[i - 1],
        d1 = data[i],
        d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    ...
  }

这是Mike的一个示例提供的代码。

首先,您可以获得鼠标位置上使用的缩放比例的x-value。然后使用平分线来获得基础数据的两个最接近的值。然后,您选择合适的一个并可以显示它。

如果需要,可以在两个数据点之间手动插值,也可以使用路径元素的getPointAtLength并计算路径使用的插值。

只需像在任何其他处理程序函数中一样访问绑定数据:

function mousemoved(d,i) {
    // do something with d and i
}