我有一个文本,我想对其应用两个不同的关键帧动画,名为 animeUp
和 animeDown
。另外,我希望能够使用 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/