如何改变css3动画状态

时间:2016-09-27 18:58:08

标签: javascript css css3 animation

我要做的是播放和暂停 css3动画
从这个链接: How to pause and resume CSS3 animation using JavaScript?我学会了如何暂停动画 我也实现了它但是当我暂停动画时它会回到初始状态 我如何从上一个状态暂停或恢复(暂停或播放)而不是回到初始状态?
这是我的代码::

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Teleprompter</title>
<style>
.demo{
     width: 500px;
    height: 500px;
}
.demo1
{
    -webkit-animation-name: example; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 4s;

}
.demo1:hover
{
 -webkit-animation-play-state: paused;  /* Chrome, Safari, Opera */
animation-play-state: paused;       
}
.PauseAnimation{
     -webkit-animation-play-state: paused;  /* Chrome, Safari, Opera */
     animation-play-state: paused;
}
.RunningAnimation{
     -webkit-animation-play-state: running;  /* Chrome, Safari, Opera */
     animation-play-state: running;
}
@-webkit-keyframes example {
    from {transform:translateY(0px);}
    to {transform:translateY(-100px);}
}
@keyframes example {
   from {transform:translateY(0px);}
   to {transform:translateY(-100px);}
}
</style>
<script>
    function f1()
    {
        var flag=0;
        var s = document.getElementById('btn1').innerHTML;
        if(s=="Play"){
            document.getElementById('btn1').innerHTML='Pause';  
            if(flag==0){
                document.getElementById('p1').className='demo1';
                flag=flag+1;
                return;
            }
            document.getElementById('p1').className='RunningAnimation';

            return;
        }
       else if(s=='Pause'){
        document.getElementById('btn1').innerHTML='Play';   
        document.getElementById('p1').className='PauseAnimation';
        return;
    }
    else return;
}
function f2(){
    document.getElementById('div1').contentEditable=true;       
}

</script>
</head>

<body >
<div class="demo"  id="div1">
<div id="p1">
<br><br><br><br><br>
<p>
Hello!!!
<br>
Hello world!!!
<br>
Hello html!!!
<br>
Hello javascript!!!
<br>
Hello css!!!
<br>
Hello animation!!!
</p>
<br id="br1"><br><br>
</div>
</div>
<button onClick="f1()" id="btn1">Play</button>
<button onClick="">Stop</button>
<button onClick="f2()">Edit text</button>
</body>
</html>

我的代码中有没有错误?

1 个答案:

答案 0 :(得分:2)

在您的脚本中更改此

document.getElementById('p1').className='RunningAnimation';

到这个

document.getElementById('p1').classList.toggle('RunningAnimation');

还有这个

document.getElementById('p1').className='PauseAnimation';

到这个

document.getElementById('p1').classList.toggle('PauseAnimation');

您不会更改类名,但可以切换它们。这是工作演示:jsFiddle