我选择了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);

答案 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;
}