将 child 从一个 parent 移动到另一个 parent 时的翻译动画

Translation animation when moving child from one parent to another parent

我正在尝试制作 connect4 HTML 游戏,我知道我最好使用 canvas 元素而不是 [=16] 的网格=]s 但是在像这样移动 HTML 元素时是否可以制作 css 动画的过渡转换类型( 使用 appendChild

const row1 = document.getElementById("row1")
const row2 = document.getElementById("row2")
const ball = document.getElementById("TheBall")

ball.addEventListener("click", (event, element) => {
  let rowNum = parseInt(ball.dataset.row)
  
  if(rowNum==1) {
    row2.appendChild(ball)
    ball.dataset.row = 2
  } else {
    row1.appendChild(ball)
    ball.dataset.row = 1
  }
})
#main {
    left:100px;
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
  }
  
  #main div {
    margin: 50px 0;
    width: 50px;
    height: 50px;
  }
  
  #TheBall {
    width: auto;
    height: auto;
    background-color: red;
    border-radius: 100%;
  }
  
  
<div id="main">
    <div id="row1"> </div>
    <div id="row2">
      <div id="TheBall" data-row=2></div>
    </div>
  </div>

点击红点切换球的位置

您可以使用animationend检查动画何时结束并在 div 之间移动球元素

const row1 = document.getElementById("row1")
const row2 = document.getElementById("row2")
const ball = document.getElementById("TheBall")

ball.addEventListener('animationend', () => {
  ball.classList.remove("animate-ball");
  ball.style.animation = "";
  let rowNum = parseInt(ball.dataset.row)
  if (rowNum == 1) {
    row2.appendChild(ball)
    ball.dataset.row = 2
  } else {
    row1.appendChild(ball)
    ball.dataset.row = 1
  }
});
ball.addEventListener("click", (event, element) => {
  let rowNum = parseInt(ball.dataset.row)
  if (rowNum == 1) {
    ball.style.animation = "MoveDown 1s linear";
  } else {
    ball.style.animation = "MoveUp 1s linear";
  }
  ball.classList.add("animate-ball");
})
#main {
  left: 100px;
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
}

#main div {
  margin: 50px 0;
  width: 50px;
  height: 50px;
}

#TheBall {
  position: relative;
  width: auto;
  height: auto;
  background-color: red;
  border-radius: 100%;
}

.animate-ball {
  animation-iteration-count: 1;
  position: absolute;
  bottom: 0;
}

@keyframes MoveUp {
  0% {
    top: -50px;
  }
  100% {
    top: -100px;
  }
}

@keyframes MoveDown {
  0% {
    top: 0;
  }
  100% {
    top: 50px;
  }
}
<div id="main">
  <div id="row1"> </div>
  <div id="row2">
    <div id="TheBall" data-row=2></div>
  </div>
</div>