无法更改d3.js矩形的填充颜色。

3

我有这段代码 -

bars.
  append('rect')
  .attr('x', 0)
  .attr('y', (d, i) ->
    return yScale(i)
  ).attr('width', (datum) ->
    return xScale(datum.freq)
  )
  .attr('height', barHeight)
  .attr('fill', 'blue')
  .attr('class', 'bar')
  .on('click', ->
    bars.selectAll('rect').attr('fill', '#0000ff')
    currentFill = d3.select(this).style('fill')
    nextColor = {}
    if currentFill == '#0000ff'
      nextColor = '#ff0000'
    else
      nextColor = '#0000ff'
    d3.select(this).style('fill', nextColor)
  )

然而,bars.selectAll('rect')并未改变矩形的颜色。为什么?

bars.selectAll(...) 正在将颜色从蓝色改变为蓝色。你想要发生什么? - Lars Kotthoff
1个回答

5

attr()替换为style()。因此,您的代码行应为:

bars.selectAll('rect').attr('fill', '#0000ff')

should be:

bars.selectAll('rect').style('fill', '#0000ff')

1
实际上,从我的上面的fiddle中看来,两者之间的区别只存在于CSS也存在的情况下:样式会覆盖它,填充则不会。@praks,你的示例中是否有CSS? - Jonah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接