如何使用变换翻译动画更改元素的父元素?

tur*_*452 3 html javascript css

在此输入图像描述

我想将一个元素从一个父级移动到另一个父级。在这里我想应用 CSS 变换动画。

function abc() {
let child = document.querySelector("#child");
let parent = document.querySelector("#div_b");

parent.appendChild(child);
}
Run Code Online (Sandbox Code Playgroud)
<div id="div_a" style="height:30px; width:30px; background-color:yellow;">
    <div id="child" class="new-box">
        <div style="width: 20px; height: 20px; background-color: green;"></div>
    </div>
  </div>

  <div id="div_b" style="height:30px; width:30px; background-color:red;">
  </div>
  
<button onclick="abc()">move</button>
Run Code Online (Sandbox Code Playgroud)

A H*_*rth 5

您可以找出该元素当前所在的位置,将其移动到新的父级,并找出它现在所在的位置,将其放回其原始父级并设置动画以使其转换到新位置。

动画完成后,您将元素放入其新位置(即放入其新父元素)。

function abc() {
  const child = document.querySelector("#child");
  const parent = document.querySelector("#div_b");
  const parentOriginal = document.querySelector("#div_a");
  parentOriginal.appendChild(child); //put back to where it was
  const x0 = child.getBoundingClientRect().left;
  const y0 = child.getBoundingClientRect().top;

  parent.appendChild(child);
  const x1 = child.getBoundingClientRect().left;
  const y1 = child.getBoundingClientRect().top;
  parentOriginal.appendChild(child);
  child.style.setProperty('--dx', (x1 - x0) + 'px');
  child.style.setProperty('--dy', (y1 - y0) + 'px');
  child.addEventListener('animationend', function() {
    parent.appendChild(child);
    child.classList.remove('move');
  });
  child.classList.add('move');
}
Run Code Online (Sandbox Code Playgroud)
.move {
  animation: move 2s linear 1;
}

@keyframes move {
  0% {
    transform: translateX(0) translateY(0);
  }
  100% {
    transform: translateX(var(--dx)) translateY(var(--dy));
  }
}
Run Code Online (Sandbox Code Playgroud)
<div id="div_a" style="height:30px; width:30px; background-color:yellow;">
  <div id="child" class="new-box">
    <div style="width: 20px; height: 20px; background-color: green;"></div>
  </div>
</div>

<div id="div_b" style="height:30px; width:30px; background-color:red;">
</div>

<button onclick="abc()">move</button>
Run Code Online (Sandbox Code Playgroud)