JS
ref – https://codepen.io/anon/pen/VXMdwE
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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) { childA.classList.add('transition'); childB.classList.add('transition'); 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); childA.classList.remove('transition'); childB.classList.remove('transition'); childB.removeAttribute('style'); childA.removeAttribute('style'); }, 300); } swapDone = true; }); |
HTML
1 2 3 4 5 6 7 8 |
<ul class="container"> <li class="child" id="childA">A</li> <li class="child" id="childB">B</li> </ul> <button> Swap position 2 </button> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
html, body { width: 100%; height: 100%; } body { display: flex; flex-direction: column; align-items: center; justify-content: center; background-color: beige; } .child { display: flex; align-items: center; justify-content: center; width: 300px; height: 50px; } .child.transition { transition: transform ease-in 0.3s; } .child:first-child { background-color: tomato; } .child:nth-child(2) { background-color: royalblue; } button { padding: 5px; margin-top: 2rem; } |