[英]How to add tooltip to a react + d3 grouped and stacked bar chart?
我创建了一个带有 react + d3 的堆叠和分组条形图,我想添加工具提示,我尝试了不同的方法,但都没有奏效。 工具提示的代码如下所示:
const tooltip = select(svgRef.current) .append("div") .style("position", "absolute") .style("visibility", "visible") .style("background-color", "black") .style("border", "solid") .style("border-width", "1px") .style("border-radius", "5px") .style("padding", "10px") .html("<p>I'm a tooltip written in HTML</p>"); svg .select(".barreact") .on("mouseover", function () { return tooltip.style("visibility", "visible"); }) .on("mousemove", function () { return tooltip .style("top", event.pageY + "px") .style("left", event.pageX + "px"); }) .on("mouseout", function () { return tooltip.style("visibility", "hidden"); });
任何帮助使它工作将不胜感激
使用 SVG foreignObjects
将 HTML 附加到 SVG:
const tooltip = select(svg)
.append("foreignObject")
.attr("width", 180);
const tooltipDiv = tooltip
.append("xhtml:div")
.html("<p>I'm a tooltip written in HTML</p>");
请注意,我们只设置了宽度。 高度是通过查看宽度设置为 div 的高度来动态计算的:您也可以执行相反的操作,设置高度并内省宽度:
bars.on("mousemove", function () {
const htmlContentHeight = tooltipDiv.node().getBoundingClientRect()
.height;
tooltip.attr("height", htmlContentHeight);
tooltip.raise();
return tooltip
.attr("x", event.pageX)
.attr("y", event.pageY - htmlContentHeight);
})
由于 SVG 没有 z-index,我们必须将最后一个元素放在 SVG 的顶部,我们可以使用selection.raise
来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.