【发布时间】:2021-03-06 17:44:57
【问题描述】:
我正在尝试使用 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>
)
}
【问题讨论】:
-
工具提示的 css 是什么样的?
-
所有的css当前都在代码中——位置:绝对等
标签: javascript html reactjs d3.js