我有一个文本,我想对其应用两个不同的关键帧动画,分别为animeUp
和animeDown
。另外,我希望能够使用javascript控制动画。
期望的结果是启动animeUp
动画的JavaScript代码和启动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>
答案 0 :(得分:1)
为每个动画创建一个类,然后在两者之间切换。
我报废了一个演示,没什么花哨的只是为了传达想法。
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>