我编写了以下代码(这是一个玩具示例,jsfiddle 上的 here)来在悬停形状时显示标签:
var lbl;
var svg = d3.select("#chart").append("svg")
.attr("width", 200)
.attr("height", 200);
svg.append("rect")
.attr("x", 50)
.attr("y", 0)
.attr("width",50)
.attr("height",50)
.attr("label","first line"+"<br/>"+"second line")
.style("fill", "yellow")
.on("mouseover",function() {
var th=d3.select(this);
lbl=svg.append("text")
.attr("x", th.attr("x")*1+th.attr("width")/2)
.attr("y", th.attr("y")*1+th.attr("height")/2)
.attr("dy", "0.5em")
.style("text-anchor", "middle")
.style("visibility", "visible")
.attr("pointer-events", "none")
.text(th.attr("label"));
})
.on("mouseout",function(){
lbl.remove();
});
如何以 html 格式呈现标签?
最佳答案
你可以制作一个div并给css position:absolute
这样你现在就可以将它定位到 w.r.t.计算顶部和左侧。
还可以在 div 中设置文本,如 .html("your html<br> text")
var th=d3.select(this);
lbl=d3.select("#chart").append("div")
.attr("class", "tooltip")
.style("left", (th.attr("x")*1+th.attr("width")/2) + "px")
.style("top", (th.attr("y")*1+th.attr("height")/2) + "px")
.html(th.attr("label"));
工作代码here
关于javascript - d3 元素内的 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375785/