程式碼
// html
<div class="basicTooltip"></div>
// js
const svg = d3
.select(".basicTooltip")
.append("svg")
.attr("width", 300)
.attr("height", 200);
// 圓點
const circle = svg
.append("circle")
.attr("id", "dot")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 40)
.attr("fill", "#69b3a2");
// 建立Tooltip
const tooltip = d3
.select(".basicTooltip")
.style("position", "relative")
.append("div")
.style("position", "absolute")
// 初始隱藏tooltips
.style("display", "none")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px")
.html(
`<p class="text-center fw-bold">我是 Tooltip!</p>
<p>這邊可以隨意放入任何想放的資料</p>
<p>甚至圖片也可以!</p>
<div class="text-center">
<img style="width:120px; height:130px"
src='./img/index/pie.png'></img>
</div>`
);
// 加上滑鼠事件
circle
.style("cursor", "pointer")
.on("mouseover", () => tooltip.style("display", "block"))
// 設定hover時顯示tooptip,並設定tooptip位置
.on("mousemove", () =>
tooltip.style("top", "200px").style("left", "280px")
)
// 滑鼠移開時隱藏tooltips
.on("mouseleave", () => tooltip.style("display", "none"));
程式碼
// html
<div class="advancedTooltip"></div>
// js
const tooltipsData = [
{ r: 17, x: 134, y: 181 },
{ r: 23, x: 294, y: 131 },
{ r: 14, x: 84, y: 273 },
{ r: 9, x: 323, y: 59 },
{ r: 18, x: 172, y: 251 },
{ r: 26, x: 404, y: 154 },
];
// 建立SVG
const svg = d3
.select(".advancedTooltip")
.style("position", "relative")
.append("svg")
.attr("width", 500)
.attr("height", 400);
// 設定顏色
const rData = tooltipsData.map((i) => i.r);
const colors = d3
.scaleOrdinal(d3.schemeTableau10)
.domain(rData);
// 建立圓點們
const dots = svg
.selectAll("circle")
.data(tooltipsData)
.enter()
.append("circle")
.attr("r", (d) => d.r)
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y)
.attr("fill", (d) => colors(d.x))
.style("cursor", "pointer");
// 建立tooltip
const tooltip = d3
.select(".advancedTooltip")
.append("div")
.style("display", "none")
.style("position", "absolute")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "2px")
.style("border-radius", "5px")
.style("padding", "5px");
dots
// 顯示tooltip
.on("mousemove", (e) => {
// 抓圓點位置
let pt = d3.pointer(event, e.target);
tooltip
.style("display", "block")
// 設定tooltips位置
.style("left", `${pt[0] + 30}px`)
.style("top", `${pt[1]}px`)
// 抓到綁定在DOM元素的資料
.html("圓半徑:" + e.target.__data__.r);
})
.on("mouseleave", () => {
tooltip.style("display", "none");
});