0
点赞
收藏
分享

微信扫一扫

用js控制css的animation动画的小想法

booksmg2014 2022-02-25 阅读 113
csshtml

之前写作业想要实现通过点击触发animation动画的效果。理论上可以用js修改css达到目的,不过我不晓得怎样修改keyframes里的内容,在网上也没找到合适的方法。一开始我的思路是写两份css,一份初始状态,一份是点击之后需要显示的效果,但在实际操作中发现如果直接替换css的话,动画效果并不会出现,只能显示动画结束时的状态。所以后面我改变了做法,不改变文件,而是改变css代码块。简单来说就是对同一内容写两份不同的css代码块,通过更换class的值达到修改css的效果。

实例:

html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" src="index.css" type="text/css">
    <script type="text/javascript" src="control.js"></script>
</head>
<body>
    <div id="pic" class="pic1">
        <img src="pic.jpg">
    </div>
  <button type="button" onclick="next()">start</button>

</body>
</html>

css

.pic1{           /*初始状态*/
    position: relative;
    width:50%;
    top:50%;
}

/*动画*/
.pic2{
    position: relative;
    width:50%;
    top:50%;
    animation-name: pic2;
    animation-duration: 3s;
    animation-fill-mode: both;
}

@-webkit-keyframes pic2{     /*适用于chrome*/
    0% {
        width:90%;
        top:50%;
    }
    50%{
        width:50%;
        top:50%;
    }
    100% {
        width:50%;
        top:10%;
    }
}

 js

function next(){
    document.getElementById("pic").className="pic2";
}

这样就实现了对animation的控制。

举报

相关推荐

0 条评论