当多个正在运行时,是否可以检测到最后一次CSS转换的结束?

时间:2017-01-13 21:59:26

标签: html css css-transitions css-animations

如果一个元素的css属性有多个已更改并且它们具有不同的转换持续时间,那么有没有办法检测上一个/最长运行转换的完成情况。

示例:

<style>
.box {
    width: 100px;
    height: 100px;
    transition: width 0.5s, height 6s;
}

.animate {
    width: 400px;
    height: 400px;
}
</style>

<div class="box"></div>

<script>

  // I want to run some code after both the width and height transitions
  // are complete

  // Listening for transitionend events will fire on every transition 
  // that ends. So in this case, both width and height. Assume I don't 
  // know how many properties are being transitioned.
  $('.box').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function(ev) {
       // ...
  });
  $('.box').addClass('animate');

</script>

2 个答案:

答案 0 :(得分:0)

您可以找出过渡次数,然后将其计算下来。

var box = document.getElementsByClassName('box')[0];
numTransitions = getComputedStyle(box).transition.split(',').length;

如果你的CSS不干净,那可能很脆弱,但也许你可以控制它

答案 1 :(得分:0)

是的,这有可能,但有点棘手。您从过渡属性中提取持续时间(和延迟),并找到具有最高值的持续时间(和延迟)。由于transitionEnd具有(transition)propertyName值,现在您只需将其与提取的属性进行比较。 Example is here。 (请注意,您必须等待6秒才能发生事情)

function getMaxTransitionDuration(el) {
    // small helper to extract the values
    function extract(str) {
        return str
          .replace(/[A-Z]/gi, "")
          .split(", ")
          .map(parseFloat);
    };
  // get the current style
  var style = getComputedStyle(el);
  // get all transition properties
  var props = style.transitionProperty.split(", ");
  // we need delay and duration
  var delays = extract(style.transitionDelay);
  var durations = extract(style.transitionDuration);

  // combinate delay and duration
  var totals = durations.map(function(v, i) {
    return v + delays[i];
  });

  // find the property with longest value
  var max = totals[0]; 
  var maxIndex = 0;
  for (var i = 1; i < totals.length; i++) {
    if (totals[i] > max) {
      maxIndex = i;
      max = totals[i];
    }
  }
  // and return this property
  return props[maxIndex];
}

$('.box').on('transitionend', function(ev) {
    var lastProp = getMaxTransitionDuration(this);
    if (ev.originalEvent.propertyName == lastProp) { 
      // here we are.....
    }
});

$('.box').addClass('animate');