D3(带角度)无法在 div 中插入范围

  • 本文关键字:div 插入 范围 D3 d3.js
  • 更新时间 :
  • 英文 :


我有这个工作代码。 其中 D3 部分基本上是:

var bar = chart.append("div").attr("class", "chart")
             .selectAll('div')
            .data(scope.data.sort().reverse()).enter().append("div")
             .transition().ease("elastic")
             .style("width", function(d) { return (d[0]/sum)*attrs.chartWidth + "px"; })//This is where I base the width as a precentage from the sum and calculate it according to the chart-width attribute
            .style("background-color",function(){i++;if (i<=colors.length-1){return colors[i-1]} else {return colors[(i-1)%colors.length]}}).text(function(d) { return d[1] ; }) 

但是当我尝试在链接中append("span")时,文本将在跨度上而不是在父div 中。 文本只是消失,开发控制台没有显示跨度和文本的线索。 还尝试了insert("span"),甚至更换了.text .html(function(d){return "<span>"+d[1]+"</span>"}

两者都不行。

有什么线索吗?谢谢!

问题是您正在链中启动transitiontransition对象提供了许多功能,就像普通d3.selection一样,包括.remove.text.html,但不允许.append操作。

您应该重构代码以读取:

    var bar = chart.append("div").attr("class", "chart")
        .selectAll('div')
        .data(scope.data.sort().reverse()).enter().append("div");
    bar
        .transition().ease("elastic")
        .style("width", function(d) { return (d[0]/sum)*attrs.chartWidth + "px"; })//This is where I base the width as a precentage from the sum and calculate it according to the chart-width attribute
        .style("background-color",function(){i++;if (i<=colors.length-1){return colors[i-1]} else {return colors[(i-1)%colors.length]}}) }) 
    bar.append('span')
       .text(function(d) { return d[1] });

演示

作为旁注,在选择background-color时,您不需要自己维护索引变量,d3将数据d和索引i传递给您提供给.style的 setter 函数:

.style("background-color",
       function(d, i){  // <-- 'd' and 'i' are passed by d3
            if (i<=colors.length-1)
                 {return colors[i-1]} 
            else {return colors[(i-1)%colors.length]}}) 
 }) 

最新更新