动画 div 个元素

Animate div elements

如何让这些 div 元素在相互碰撞后停止并 return 回到它们的起始位置?我尝试在函数中调整添加到像素,但没有用。

例如,我试过 elem.style.right = pos + '100px'。当我尝试这个时,div 元素最终根本没有移动。

您可以尝试某种形式的碰撞检测。请参阅下面的 collisionDetection 方法。

let leftIntervalId;

var leftElem = document.getElementById("myAnimation");

function myMove() {

  var pos = 0;
  leftIntervalId = setInterval(frame, 10);

  function frame() {
    if (pos == 350) {
      clearInterval(leftIntervalId);
    } else {
      pos++;
      leftElem.style.top = pos + 'px';
      leftElem.style.left = pos + 'px';
    }
  }
}

const rightElem = document.getElementById("Animation");

function Move() {

  var pos = 0;
  var id = setInterval(frame, 10);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      rightElem.style.top = pos + 'px';
      rightElem.style.right = pos + 'px';
      collisionDetection(parseInt(leftElem.style.left.replace(/px/, "")), pos,
        leftIntervalId, id);
    }
  }
}

function collisionDetection(leftPos, rightPos, leftIntervalId, rightIntervalId) {
  if (leftPos + 100 > 400 - rightPos) {
    clearInterval(leftIntervalId);
    clearInterval(rightIntervalId);
    setTimeout(function() {
        leftElem.style.top = '0px';
        leftElem.style.left = '0px';
        rightElem.style.top = '0px';
        rightElem.style.right = '0px';
      },
      500);
  }
}
#myContainer {
  width: 400px;
  height: 400px;
  position: relative;
  background: #eee;
}

#myAnimation {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}

#Animation {
  width: 50px;
  height: 50px;
  position: absolute;
  right: 0;
  background-color: blue;
}
<p>
  <button onclick="myMove(); Move()">Click Me</button>
</p>

<div id="myContainer">
  <div id="myAnimation"></div>
  <div id="Animation"></div>
</div>