如何在当前位置开始另一个动画?

How to start another animation on current position?

这是我的盒子

<div class="mybox"></div>

我有一个动画

.mybox{
  animation:right 5s;
  animation-fill-mode:forwards;
  padding:50px;
  width:0px;
  height:0px;
  display:block;
  background-color:black;
}
@keyframes 

right{from{left:0px;}to{left:300px 
;}}
@keyframes 
left{from{right:0px;}to{right:300p 
 x;}}

我有两个按钮

<button onclick="leftFunction">left</button>
<button onclick="rightFunction">right</button>

然后如果我向左单击它会在向左移动时向左移动然后我向右单击我想停止向左动画并向右移动但向右动画必须从当前位置开始而不是传送并向右移动。

请帮忙:( 我是堆栈溢出的新手

这是js

function leftFunction() {
             
document.getElementById("myDIV").style.animation 
= "left 4s";
}
function rightFunction() {
              
 document.getElementById("myDIV").style. 
animation = "right 4s";
}

我发现您发布的代码存在很多问题,但您的方向是正确的。

  1. 您的 DOM 方法正在查找 ID 为 myDIV 的元素,但该元素不存在,我将其更改为 document.querySelector(".mybox"),因为那是 class 你的名字 div.

  2. 您没有在 onclick 处理程序上调用函数调用,不确定您是否正在发生任何事情...添加 () 调用它 onclick .

  3. 您的代码布局没有遵循正常的间距约定,但是很难将代码写入堆栈溢出,所以我理解。我进行了必要的更改。

  4. 您正在为您的 div 设置位置值,但没有声明 position 属性。位置默认为 static,不响应 leftright。我使用了 relative,因为这将在文档流中保留 div。

  5. 更改一个动画的 left 和另一个动画的 right 将分别保持先前的左值或右值,并可能导致您的 div 缩小或增大不料。我将其更改为仅影响 left 属性.

现在是解决方案

更改关键帧以仅更新 left 属性。从 onclick 调用函数并传入 event 对象。这将允许您只有一个函数来处理动画的变化,并且可以使用事件目标的 innerHTML 来设置所需动画的名称。

利用 CSS 自定义属性,以便可以在 javascript 中更改值,并使您的 from 属性从自定义 属性 开始。在这种情况下 --cur-pos.

当函数被调用时,获取div元素,找到它的计算left值与document.getComputedStyle(),然后更新自定义属性--cur-pos 具有该值。这样动画总是从 div 当前所在的位置开始。

瞧瞧!你应该可以走了。您可能需要调整起始 --cur-pos 值以使 div 从您想要的位置开始,并更新 to 值以在您想要的位置结束,只需确保选择 leftright 用于更新水平位置,而不是两者。

function changeAnimation(e) {
  const box = document.querySelector(".mybox")
  const pos = window.getComputedStyle(box).left
  box.style.setProperty("--cur-pos", pos)
  box.style.animationName = e.target.innerHTML
}
.mybox {
  --cur-pos: 150px;
  width: 100px;
  height: 100px;
  background-color: black;
  position: relative;
  animation: right 4s forwards;
}

@keyframes right {
  from { left: var(--cur-pos); }
  to { left: 300px; }
}

@keyframes left {
  from { left: var(--cur-pos); }
  to { left: 0px; }
}
<div class="mybox"></div>
<button onclick="changeAnimation(event)">left</button>
<button onclick="changeAnimation(event)">right</button>