我有这个工作代码。 其中 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>"}
两者都不行。
有什么线索吗?谢谢!
问题是您正在链中启动transition
。transition
对象提供了许多功能,就像普通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]}})
})