【问题标题】:Transition and opacity does not work well together过渡和不透明度不能很好地协同工作
【发布时间】:2014-11-05 20:27:55
【问题描述】:

我为点击触发的过渡设置了 1500 毫秒的持续时间

在第一次运行时,转换的持续时间似乎为 0 毫秒,这不是预期的 -_-

带有相应小提琴的最小示例(http://jsbin.com/pasodopeyati/3/edit):

// create svg element
var svg = d3.select("body").append("svg").attr('width', 200).attr('height', 200);

// add 4 red circles
svg.selectAll('circle').data([{'n': 0}, {'n': 1}, {'n': 2}, {'n': 3}])
  .enter()
  .append('circle')
  .attr({
    cx: function(d, i) { return (i % 2) * 50 + 50;},
    cy: function(d, i) { return Math.floor(i / 2) * 50 + 50;},
    r:10,
    fill: 'red'
  });


// counter
var i = 0;  

// create button and bind on click
d3.select("body").append('button').text('fade').on('click', function () {
  // fade 3 circles alternatively (cf. counter)
  svg.selectAll('circle')
  .transition()
  .duration(2000)
  .attr('opacity', function(d) { return d.n == i ? 1 : 0.1});

  i = (i + 1) % 4;
});

试试吧!您会注意到第一次点击会立即淡出 3 个圆圈,并且从该点击开始,它将按预期以 1500 毫秒的持续时间进行过渡。

如何使第一次转换的持续时间为 1500 毫秒?

奖励:为什么我的代码会这样?

【问题讨论】:

    标签: d3.js transition opacity


    【解决方案1】:

    实际上我认为opacitystyle 参数而不是svg attribute。所以你也可以改变你的路线:

    .attr('opacity', function(d) { return d.n == i ? 1 : 0.1})

    .style('opacity', function(d) { return d.n == i ? 1 : 0.1})

    结果相同。

    【讨论】:

      【解决方案2】:

      当您创建圆圈时,您没有指定任何不透明度,因此没有从/到过渡。试试这个:

        .attr({
          cx: function(d, i) { return (i % 2) * 50 + 50;},
          cy: function(d, i) { return Math.floor(i / 2) * 50 + 50;},
          // need this starting value
          opacity: 1
          r:10,
          fill: 'red'
        });
      

      【讨论】:

        猜你喜欢
        • 2012-01-07
        • 2016-12-08
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-14
        • 2018-01-18
        • 1970-01-01
        相关资源
        最近更新 更多