javascript - d3 元素内的 html 标签

标签 javascript html d3.js hover

我编写了以下代码(这是一个玩具示例,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/

相关文章:

javascript - 页面重新加载后保留按钮属性

html - textarea 根据里面的内容调整大小

javascript - 添加数字格式作为动画数字中的货币(10,000)

javascript - d3 桑基图 - 如何设置 y 位置

javascript - 流图 : two questions

javascript - 如何将 codeigniter 的 CSRF token 传递给 Paypal Express Checkout?

javascript - React Modal 确认无法正常工作

javascript - 向 d3 条形图添加标签

javascript - 根据用户账户状态弹出

javascript - 如何在浏览器上运行text-to-svg?