[英]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.