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

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


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


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


注意:我们想要关键帧动画,因为它们是......


//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>


当年话下
浏览 264回答 1
1回答

qq_花开花谢_0

为每个动画创建一个类并在两者之间切换。我拼凑了一个演示,没有什么太花哨的,只是为了传达这个想法。document.querySelector('.up').onclick = (e) => {&nbsp; document.getElementById("Text").classList.add("animeup");&nbsp; document.getElementById("Text").classList.remove("animedown");&nbsp; e.target.disabled = "true";&nbsp; document.querySelector('.down').removeAttribute("disabled");}document.querySelector('.down').onclick = (e) => {&nbsp; document.getElementById("Text").classList.remove("animeup");&nbsp; document.getElementById("Text").classList.add("animedown");&nbsp; document.querySelector('.up').removeAttribute("disabled");&nbsp; e.target.disabled = "true";}html {&nbsp; overflow: hidden;}#Text {&nbsp; position: absolute;&nbsp; overflow: hidden;&nbsp; font-family: 'Open Sans', sans-serif;&nbsp; font-weight: bold;&nbsp; font-size: 7.5vw;&nbsp; color: red;&nbsp; left: 1vw;&nbsp; top: -50vh;&nbsp; animation-fill-mode: forwards;}@-webkit-keyframes animeUp {&nbsp; from {&nbsp; &nbsp; top: 10vh&nbsp; }&nbsp; to {&nbsp; &nbsp; top: -50vh&nbsp; }}@-webkit-keyframes animeDown {&nbsp; from {&nbsp; &nbsp; top: -50vh&nbsp; }&nbsp; to {&nbsp; &nbsp; top: 10vh&nbsp; }}.animeup {&nbsp; animation: animeUp 0.5s ease-out;}.animedown {&nbsp; animation: animeDown 0.5s ease-in;}<button class="up" disabled>Up</button><button class="down">Down</button><div class="container">&nbsp; <p id="Text">Tutorial</p></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript