javascript - 通过JavaScript控制单个元素的多个关键帧动画

标签 javascript html css

我有一个文本,我想对其应用两个不同的关键帧动画,名为 animeUpanimeDown。另外,我希望能够使用 javascript 控制动画。

期望的结果是一行 javascript 代码启动 animeUp 动画,另一行代码启动 animeDown...

我尝试通过添加更改 animation-play-state 的 CSS 类来播放和暂停动画,但使用这种方法我只能控制其中一个动画!

注意:我们想要关键帧动画……

//pause the animation at first
document.getElementById("Text").classList.add("paused");

//after 2 seconds initiate the animation
setTimeout(function(){  
document.getElementById("Text").classList.add("played");
}, 2000)
html{
    overflow:hidden;
}

#Text{
    position: absolute;
    overflow: hidden;  
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    font-size: 7.5vw;
    color: rgb(242, 242, 242);
    left: 1vw;
    top: -45vh;
    animation: animeUp 0.5s ease-out ;
    animation: animeDown 0.5s ease-in ;
    animation-fill-mode: forwards;
}

@-webkit-keyframes animeUp {
   from { top: 10vh }
   to   { top: -50vh }
}

@-webkit-keyframes animeDown {
   from { top: -50vh }
   to   { top:  10vh }
}

.paused {
   -webkit-animation-play-state: paused !important; 
}

.played {
   -webkit-animation-play-state: running !important; 
}
<!DOCTYPE html>
<html>
<head>
</head>

<body>
<div class = "container">
 <p id="Text">Tutorial</p>
</div>
</body>

</html>

最佳答案

为每个动画创建一个类并在两者之间切换。

我拼凑了一个演示,没有什么特别花哨的,只是为了让大家了解这个想法。

document.querySelector('.up').onclick = (e) => {
  document.getElementById("Text").classList.add("animeup");
  document.getElementById("Text").classList.remove("animedown");
  e.target.disabled = "true";
  document.querySelector('.down').removeAttribute("disabled");
}

document.querySelector('.down').onclick = (e) => {
  document.getElementById("Text").classList.remove("animeup");
  document.getElementById("Text").classList.add("animedown");
  document.querySelector('.up').removeAttribute("disabled");
  e.target.disabled = "true";
}
html {
  overflow: hidden;
}

#Text {
  position: absolute;
  overflow: hidden;
  font-family: 'Open Sans', sans-serif;
  font-weight: bold;
  font-size: 7.5vw;
  color: red;
  left: 1vw;
  top: -50vh;
  animation-fill-mode: forwards;
}

@-webkit-keyframes animeUp {
  from {
    top: 10vh
  }
  to {
    top: -50vh
  }
}

@-webkit-keyframes animeDown {
  from {
    top: -50vh
  }
  to {
    top: 10vh
  }
}

.animeup {
  animation: animeUp 0.5s ease-out;
}

.animedown {
  animation: animeDown 0.5s ease-in;
}
<button class="up" disabled>Up</button>
<button class="down">Down</button>

<div class="container">
  <p id="Text">Tutorial</p>
</div>

关于javascript - 通过JavaScript控制单个元素的多个关键帧动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076472/

相关文章:

javascript - 为什么替换构造函数的原型(prototype)没有反射(reflect)在对象中?

javascript - 在 1 行中创建包含 2 个不同数据的嵌套表

javascript - 显示阵列中的特定元素?

html - 主 Div 背景颜色未出现在子 Div 上

css - 在导航栏中居中对齐菜单

html - 按钮在 Firefox 中无法正确对齐

html - span 比父 div 小,为什么?

javascript - 我可以使用类的现有实例来创建扩展子类的新对象吗?

javascript - 零剪贴板的困难

javascript - 为什么这在 Firefox、Chrome 或 Safari 上不起作用,但在 IE 上不起作用?