【问题标题】:How to get the current element height?如何获取当前元素高度?
【发布时间】:2014-11-24 17:29:39
【问题描述】:

为了让条形图中的条形平滑过渡,我需要在调用 transition() 之前设置高度。

当图表首次根据需要从图表底部呈现条形动画时:

    chart.svg.selectAll('.bar')
        .attr('y', chart.options.height)
        .attr('x', function (d) {
            return chart.xScale(d.title);
        })
        .attr('width', chart.xScale.rangeBand())
        .attr('height', function () {
            return 0;
        })
        .transition()
        .attr('y', function (d) {
            return chart.yScale(d.score);
        })
        .attr('height', function (d) {
            return chart.options.height - chart.yScale(d.score);
        });

但是,当我更改数据时,我不想将高度设置回0。相反,我需要将高度设置为矩形的当前高度。如何从attr 函数访问它?

        .attr('height', function () {
            return 0; // how do I get the current height
        })

当我登录 this 时,我可以访问 DOM 元素,但不确定从那里去哪里。我试过d3.select(this).attr('height'),但它总是返回null。

【问题讨论】:

  • 如果已经设置了高度,则不需要重新设置。有了新数据,只需添加.transition().attr("height", ...)

标签: d3.js


【解决方案1】:

正如@LarsKotthoff 在他的评论中暗示的那样,只需将您的初始抽奖与您的更新分开:

// intial draw of bars
node
  .enter()
  .append("rect")
  .attr("class", "myBars")
  .style("fill", "steelblue")
  .attr('y', config.height)
  .attr('x', function(d, i) {
    return xScale(i);
  })
  .attr('width', xScale.rangeBand())
  .attr('height', function() {
    return 0;
  });      

然后触发更新以将条从当前位置转换:

function update() {
  node = svg
    .selectAll(".myBars")
    .data(data);
  node
    .transition()
    .attr('y', function(d) {
      return yScale(d);
    })
    .attr("height", function(d) {
      return config.height - yScale(d);
    });
}

这是我可以编写的最小的example

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2011-06-29
    • 2020-03-18
    • 2016-04-27
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多