我正在尝试为d3可视化制作自定义工具提示。我将事件侦听器附加到svg onmouseover。但这给了我一个叫做"r.getAttribute is not a function"
的错误。问题出在
parseFloat(d3.select(this).attr("x")) +
parseFloat(d3.select(this).attr("width") / 2)
这是完整的代码
const w = 300,
h = 120;
const padding = 2;
const dataset = [5, 10, 15, 20, 21, 11, 25, 22, 7];
const svg = d3
.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
const colorPicker = v => {
if (v <= 20) return "#666666";
if (v => 20) return "#FF0033";
};
svg
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => (i * w) / dataset.length)
.attr("y", d => h - d * 4)
.attr("width", w / dataset.length - padding)
.attr("height", d => d * 4)
.attr("fill", d => colorPicker(d))
.on("mouseover", d => {
svg
.append("text")
.text(d)
.attr("text-anchor", "middle")
.attr(
"x",
parseFloat(d3.select(this).attr("x")) +
parseFloat(d3.select(this).attr("width") / 2)
)
.attr("y", parseFloat(d3.select(this).attr("y")) + 12)
.attr("font-family", "sans-serif")
.attr("fill", "#ffffff")
.attr("id", "tooltip");
});