我们继续这个问题,如果我希望在这张图中,鼠标移到折线上点时,显示该点所代表的后端返回数据的name,monitordate,和enqueuecount属性,代码应该怎么写
时间: 2024-02-20 08:00:04 浏览: 24
要实现鼠标悬停在折线上点时显示对应的后端返回数据属性,您需要使用D3.js中的tooltip功能。您可以在每个折线上添加一个mouseover事件监听器,当鼠标悬停在该点上时,将显示一个包含所需属性的tooltip。以下是一些示例代码,供您参考:
```javascript
// 循环遍历每个折线的数据点
d3.selectAll(".line")
.selectAll(".dot")
.data(function(d) { return d.values; })
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.enqueuecount); })
.attr("r", 5)
// 添加 mouseover 事件监听器
.on("mouseover", function(d) {
// 创建 tooltip 元素
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// 设置 tooltip 文本内容
tooltip.html(d.name + "<br/>" + d.monitordate + "<br/>" + d.enqueuecount)
// 设置 tooltip 位置
.style("left", (d3.event.pageX + 10) + "px")
.style("top", (d3.event.pageY - 28) + "px");
// 显示 tooltip
tooltip.transition()
.duration(200)
.style("opacity", .9);
})
// 添加 mouseout 事件监听器
.on("mouseout", function(d) {
// 隐藏 tooltip
d3.select(".tooltip").remove();
});
```
在上面的代码中,我们首先循环遍历每个折线的数据点,并为每个数据点添加一个mouseover事件监听器。当鼠标悬停在该点上时,我们创建一个tooltip元素,并将其文本设置为所需属性。我们还设置tooltip的位置,以便它在鼠标的旁边显示。最后,我们使用d3的过渡效果显示tooltip,并在mouseout事件发生时将其隐藏。
需要注意的是,您可能需要根据您的具体数据结构和样式来修改上面的代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)