动画元素向左移动,在 div 之外

Animating an element to go left, outside of div

我在 div 中有两个按钮,我想制作一个动画,当您单击一个按钮时,它会滑到中间,另一个被“推”开,在 div(这会使它消失,因为溢出设置为隐藏)。我通过设置按钮的左右值来实现这一点

@keyframes moveRight{
    0%{
    left: 0;}

    100%{
    left: 100px;}
}

@keyframes moveLeft{
    0%{
    right: 0;}

    100%{
    right: 100px;}

//There's a Javascript backend that animates when this is clicked

向右移动完全符合我的要求,但是当设置为向左移动时,两个项目都没有移动。我的猜测是 divs 一定无法在其左侧显示内容,这确实有道理,但提出了如何在左侧实现所需影响的问题。我可以增加 div 的大小,这样左边就有空间了,但是这样我就会失去我真正喜欢的消失效果。我怎样才能使这项工作?

感谢您的宝贵时间!

如果我理解正确的话,你可以使用这个:

@keyframes moveLeft{
    0%{
    left: 0;}

    100%{
    left: -100px;}

之所以可行,是因为您的元素未定位为 absolute。所以使用 right: 没有任何意义,因为它仅用于定位 absolute 元素。而 left 可用于 relative 定位元素:

If position: relative; - the left property sets the left edge of an element to a unit to the left/right of its normal position.

您可以阅读更多关于 left property here

如果您想通过 xy 坐标完全控制标签的位置,您必须将 position: absolute 分配给所有适用的标签(在您的情况下是 <button>s),然后将 position: relative 添加到包含它们的标签中(在您的例子中是 <div>)。所有带有 position: absolute(即 <button>s)的子标签的位置都是相对于最接近的带有 position: relative(即 <div>)的祖先标签的位置。

下面的示例或多或少地根据您的描述进行了动画处理。我将其添加为奖励,因此没有解释,因为这不是问题的一部分。如果您有任何问题 post 另一个问题 minimal reproducible example.

const menu = document.querySelector('menu');

menu.onclick = launch;

function launch(e) {
  const clicked = e.target;

  if (clicked.matches('button')) {
    if (clicked.classList.contains('ltr')) {
      clicked.classList.add('moveRight');
      document.querySelector('.rtl').classList.add('bumpRight')
    }
    if (clicked.classList.contains('rtl')) {
      clicked.classList.add('moveLeft');
      document.querySelector('.ltr').classList.add('bumpLeft');
    }
  }
}
menu {
  position: relative;
  width: 166px;
  height: 3rem;
  margin: 20px auto;
  border: 3px inset cyan;
  border-radius: 6px;
  font-size: 3rem;
  overflow: hidden;
}

button {
  position: absolute;
  top: -11.5px;
  display: inline-block;
  width: 0;
  height: 0;
  margin: 0;
  padding: 0;
  border: 0;
  font: inherit;
  cursor: pointer;
}

.ltr {
  left: -7px;
}

.rtl {
  right: 58px;
}

.moveLeft {
  animation: rightToLeft 0.5s forwards ease-in;
}

.moveRight {
  animation: leftToRight 0.5s forwards ease-in;
}

.bumpLeft {
  animation: toLeftEdge 0.6s forwards ease-out;
}

.bumpRight {
  animation: toRightEdge 0.6s forwards ease-out;
}

@keyframes leftToRight {
  0% {
    left: -7px;
  }
  50% {
    left: 98px;
  }
  100% {
    left: 70px;
  }
}

@keyframes rightToLeft {
  0% {
    right: 58px;
  }
  50% {
    right: 160px;
  }
  100% {
    right: 135px;
  }
}

@keyframes toLeftEdge {
  0% {
    left: -7px;
  }
  50% {
    left: -7px;
  }
  100% {
    left: -70px;
  }
}

@keyframes toRightEdge {
  0% {
    right: 58px;
  }
  50% {
    right: 58px;
  }
  100% {
    right: -70px;
  }
}
<menu>
  <button class='ltr'>➡️</button>
  <button class='rtl'>⬅️</button>
</menu>