javascript - 在 React/D3 中使用工具提示渲染地图
问题描述
我正在尝试使用 D3 在我的 react-app 中为我的纽约市辖区地图创建一个工具提示。我希望当我将鼠标悬停在区域上时出现工具提示,显示区域编号。现在,我可以让区域编号正确显示,但我无法让工具提示的 div 元素跟随鼠标 - 它停留在屏幕的左上角。有没有办法让 div 元素改变其相对于鼠标位置的位置?(我似乎无法让元素响应不断变化的“left”和“top”样式属性,这些属性随着鼠标位置的变化而变化。)
import React, { useEffect, useRef } from "react";
import { usePrecinctsMap } from './context/precinctsMapContext'
import * as d3 from "d3";
export const PrecinctsMap = props => {
const data = usePrecinctsMap()
const svgRef = useRef()
const containerRef = useRef()
const tltpRef = useRef()
useEffect(() => {
var tooltip = d3.select(tltpRef.current)
.attr("class", "tooltip")
.attr("position", "absolute")
.style("opacity", 0);
const svg = d3.select(svgRef.current)
.attr("height", 500)
.attr("width", "100%")
const projection = d3.geoAlbers().fitExtent([[20, 20], [300, 300]], data)
const pathGenerator = d3.geoPath().projection(projection)
svg.append("g")
.selectAll("path")
.data(data.features)
.join("path")
.attr('d', pathGenerator)
.attr('class', 'precinct')
.attr('fill', 'transparent')
.attr('stroke', '#999999')
.attr('stroke-width', '1')
.on("mouseover", function(event,d) {
tooltip.style("left", (event.pageX) + "px")
.style("top", (event.pageY - 28) + "px");
tooltip.transition()
.duration(200)
.style("opacity", .9)
;
tooltip.text(d.properties.precinct);
})
.on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
}, [containerRef.current])
return (
<div ref={containerRef} style={{ marginBottom: "2rem" }}>
<div ref={tltpRef}></div>
<svg ref={svgRef}></svg>
</div>
)
}
解决方案
将您的位置样式从绝对更改为固定。
然后在您的 javascript 中,引用 event.clientX + 'px' 和 event.clientY + 'px' 代替 pageY 和 pageX。
推荐阅读
- node.js - 在Nodejs应用程序中按下后退按钮时如何强制重新加载?
- python - 是否让 python 更紧凑,使其更高效?
- python - 尝试从本地机器导入 google colab 中的 csv 文件
- php - 在php中数学划分两个数组
- c# - 如何使用 microsoft.build.evaluation 以编程方式添加新的 dll 引用
- python - 尝试将 Pandas 系列添加到带有空白值的 Dataframe
- python - 使用 django 中的标题按字母顺序对 db 进行排序
- mqtt - 包含 Mosquitto 服务器时间的“Will message”
- php - 管理两个不同的环境 Laravel
- javascript - 在 javascript 中构建我的 Html.Partial 字符串