[英]Animate DOM elements swapping
I'd like to animate the swapping of two DOM elements in a vanilla way. 我想以一种普通的方式来动画化两个DOM元素的交换。
I have an issue at the end of the animation but I don't know what's causing it :/ 动画结束时出现问题,但我不知道是什么原因造成的:/
Here's my code: 这是我的代码:
HTML HTML
<div class="container">
<div class="child" id="childA">A</div>
<div class="child" id="childB">B</div>
</div>
<button>Swap position</button>
JS 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;
});
Here's my codepen: https://codepen.io/ChucKN0risK/pen/pLWVro 这是我的代码笔: https ://codepen.io/ChucKN0risK/pen/pLWVro
Thanks in advance ;) 提前致谢 ;)
I updated your codepen: 我更新了您的Codepen:
https://codepen.io/anon/pen/VXMdwE https://codepen.io/anon/pen/VXMdwE
The issue was that your css included this: 问题是您的CSS包含以下内容:
.child {
transition: transform ease-in 0.3s;
}
There was actually only a specific time that you wanted the transition active on the child: in the middle of the swap process. 实际上,您只希望在子级上激活过渡的特定时间:在交换过程的中间。 You didn't want the transition at the end of the swap process, so I did this:
您不希望在交换过程结束时进行转换,所以我这样做了:
.css: 的CSS:
.child.transition {
transition: transform ease-in 0.3s;
}
.js .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);
That way there's no longer a transition animation when you're removing the transition styles 这样,当您删除过渡样式时,就不再存在过渡动画
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.