我想以香草的方式设置两个DOM元素的交换动画。
我在动画结束时遇到问题,但我不知道是什么导致它:/
这是我的代码:
HTML
<div class="container">
<div class="child" id="childA">A</div>
<div class="child" id="childB">B</div>
</div>
<button>Swap position</button>
JS
const childA = document.querySelector('#childA');
const childB = document.querySelector('#childB');
const finalChildAStyle = {
x: null,
y: null,
};
const finalChildBStyle = {
x: null,
y: null,
};
let swapDone = false;
document.querySelector('button').addEventListener('click', () => {
if (swapDone === false) {
finalChildAStyle.x = childA.getBoundingClientRect().left - childB.getBoundingClientRect().left;
finalChildAStyle.y = childB.getBoundingClientRect().top - childA.getBoundingClientRect().top;
finalChildBStyle.x = childB.getBoundingClientRect().left - childA.getBoundingClientRect().left;
finalChildBStyle.y = childA.getBoundingClientRect().top - childB.getBoundingClientRect().top;
childA.style.transform = `translate(${finalChildAStyle.x}px, ${finalChildAStyle.y}px)`;
childB.style.transform = `translate(${finalChildBStyle.x}px, ${finalChildBStyle.y}px)`;
setTimeout(() => {
document.querySelector('.container').insertBefore(childB, childA);
childB.removeAttribute('style');
childA.removeAttribute('style');
}, 300);
}
swapDone = true;
});
这是我的代码:https://codepen.io/ChucKN0risK/pen/pLWVro
提前致谢;)
答案 0 :(得分:1)
我更新了您的codepen:
https://codepen.io/anon/pen/VXMdwE
问题在于你的css包含了这个:
.child {
transition: transform ease-in 0.3s;
}
实际上只有一个特定的时间,您希望在子项上激活转换:在交换过程的中间。你不想在交换过程结束时进行转换,所以我这样做了:
的CSS:
.child.transition {
transition: transform ease-in 0.3s;
}
.js
document.querySelector('button').addEventListener('click', () => {
if (swapDone === false) {
childA.classList.add('transition');
childB.classList.add('transition');
...
setTimeout(() => {
document.querySelector('.container').insertBefore(childB, childA);
childA.classList.remove('transition');
childB.classList.remove('transition');
childB.removeAttribute('style');
childA.removeAttribute('style');
}, 300);
这样,当您删除过渡样式时,不再有过渡动画