具有transitionend的动画队列

时间:2018-02-06 17:20:03

标签: javascript css

我选择了4个DOM元素,并希望使用transitionend事件逐个动画。最终我希望x的{​​{1}}和y值是动态的,因此这是在JS中完成的原因,而不仅仅是使用CSS @keyframe动画。

我目前有这个工作代码,但感觉可能有更好的方法。任何指针都会很棒。谢谢!



translate3d()

var formComponents = document.querySelectorAll('.form-component');
formComponents[0].style.transitionDelay = '2s';
formComponents[0].style.webkitTransform = 'translate3d(550px, -250px, 0)';
formComponents[0].addEventListener('transitionend', function(e) {
  formComponents[1].style.webkitTransform = 'translate3d(315px, -250px, 0)';
  formComponents[1].addEventListener('transitionend', function(e) {
    formComponents[2].style.webkitTransform = 'translate3d(150px, -250px, 0)';
    formComponents[2].addEventListener('transitionend', function(e) {
      formComponents[3].style.webkitTransform = 'translate3d(-125px, -250px, 0)';
    }, false);
  }, false);
}, false);




1 个答案:

答案 0 :(得分:1)

我相信你可以通过将.reduce()事件链接在一起的transitionend函数来完成你想要的任务。在我的示例中,我只是切换一个类,但您可以在元素上设置显式变换,而不是使用index的{​​{1}}参数计算所需的位置。请考虑以下事项:

.reduce()
const transformer = document.getElementById("transformer"),
  targets = document.getElementsByClassName("changable");

const firstEl = targets[0];

if (firstEl) {
  Array.from(targets).slice(1).reduce((prev, el) => {
    prev.addEventListener("transitionend", e => {
      el.classList.toggle("change");
    });
    return el;
  }, firstEl);

  transformer.addEventListener("click", e => {
    targets[0].classList.toggle("change");
  });
}
.changable {
  display: inline-block;
  transition: transform 200ms ease;
}

.change {
  transform: scale(1.5);
}

这是一个关闭数组索引的示例,以根据其在要转换的所有元素的数组中的位置来缩放当前元素:

<p><span class="changable">Lorem Ipsum</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span>  <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span> <span class="changable">dolumn deloris</span></p>
<button id="transformer" type="button">Transform</button>
const transformer = document.getElementById("transformer"),
  targets = document.getElementsByClassName("changable");

const firstEl = targets[0];

if (firstEl) {
  Array.from(targets).slice(1).reduce((prev, el, idx, arr) => {
    prev.addEventListener("transitionend", e => {
      el.style.transform = `scale(${(((idx+1) / arr.length)+1) *2})`;
    });
    return el;
  }, firstEl);

  transformer.addEventListener("click", e => {
    firstEl.style.transform = "scale(2)";
  });
}
.changable {
  display: inline-block;
  transition: transform 200ms ease;
}