我有一个关键帧和两个按钮.单击"前进"按钮时,我希望长方体向前移动,单击"后退"按钮时,我希望反转关键帧,使长方体向后移动.

这就是我所try 的:

const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
    box.classList.add('active');
});

document.getElementById('left').addEventListener('click', () => {
    box.style.animationDirection = 'reverse';
        // Also tried it with: box.classList.remove('active');
});
.box {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
}

.active {
  animation: move 1s forwards;
}


@keyframes move {
  from {
    left: 0;
  }
  to {
    left: 20px;
  }
}
<button id="left">&lt;</button>
<button id="right">&gt;</button>
<div class="box"></div>

推荐答案

您可以使用分配给两个不同类的两个不同动画,只需像伪切换一样添加和删除它们

const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
  box.classList.remove('moveLeft');
  box.classList.add('moveRight');
});

document.getElementById('left').addEventListener('click', () => {
  box.classList.remove('moveRight');
  box.classList.add('moveLeft');
});
.box {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
}

.active {
  animation: move 1s forwards;
}

.moveRight {
  animation: moveRight 1s forwards;
}

.moveLeft {
  animation: moveLeft 1s forwards;
}

@keyframes moveRight {
  from {
    left: 0;
  }
  to {
    left: 20px;
  }
}

@keyframes moveLeft {
  from {
    left: 20px;
  }
  to {
    left: 0px;
  }
}
<button id="left">&lt;</button>
<button id="right">&gt;</button>
<div class="box"></div>

如果未设置"使用关键帧",也可以使用过渡.相同的结果,两种不同的方法

const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
  box.classList.add('active');
});

document.getElementById('left').addEventListener('click', () => {
  box.classList.remove('active');
});
.box {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
  transition: all 1s ease-in-out;
}

.active {
  transform: translateX(20px);
  transition: all 1s ease-in-out;
}
<button id="left">&lt;</button>
<button id="right">&gt;</button>
<div class="box"></div>

Css相关问答推荐

Css扩展搜索栏,如何添加图标结束?

如果 css 仅位于 razor 页面中的一页上,我是否仍应在 wwwroot 中写入或仅将其放在页面上?

包含 N 个 React 组件的砌体网格

如何为图像堆叠效果下方的图层实现与磨砂玻璃类似的视觉效果

React Tabs 在 Tabs 之间垂直渲染标签内容

如何减少弹性项目之间的差距

如何在真实文本旁边制作文本阴影,使其看起来像 css 中的重复文本?

子菜单的背景不占用所有空间

Bootstrap 类似乎没有任何作用

:required 或 [required] CSS Select 器

CSS 使文本扩展并保持居中与圆形扩展 div 的问题

Rails 7引擎如何使未编译的样式表可用于托管应用程序?

  • 元素上的子弹来自哪里?
  • 如何更改 Angular Material 上 mat-icon 的大小?

    rotate3d 速记

    从 css 添加标题属性

    如何仅使用 CSS 制作网格(如方格纸网格)?

    Sass 无效的 CSS 错误:预期的表达式

    如何使 window.scrollTo() 效果平滑

    React - 防止父子事件触发