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

这篇博客介绍了如何通过JavaScript来控制CSS动画,实现点击按钮启动动画的效果。作者首先遇到的问题是无法直接修改keyframes内容,于是采取了创建两个不同class的方式,通过切换class实现动画的开始和结束状态。示例中展示了HTML、CSS和JavaScript的代码片段,通过为元素添加或移除'pic2'类来触发和结束动画。

之前写作业想要实现通过点击触发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的控制。

在小程序中实现CSS动画的连续播放,即一个动画播放到一半时加载另一个动画,可以通过CSS的`animation`属性和动画事件来实现。以下是一个具体的实现步骤和示例代码: ### 实现步骤: 1. **定义动画**:首先,需要在CSS中定义两个动画,分别命名为`animation1`和`animation2`。 2. **应用动画**:在需要动画的元素上应用第一个动画`animation1`。 3. **监听动画事件**:使用`animationend`事件监听第一个动画的结束,然后在回调中应用第二个动画`animation2`。 ### 示例代码: ```html <view class="animated-box" bindanimationend="handleAnimationEnd"></view> ``` ```css .animate-box { width: 100px; height: 100px; background-color: red; animation: animation1 2s forwards; } @keyframes animation1 { 0% { transform: translateX(0); background-color: red; } 50% { transform: translateX(100px); background-color: blue; } 100% { transform: translateX(200px); background-color: green; } } @keyframes animation2 { 0% { transform: translateY(0); background-color: green; } 50% { transform: translateY(100px); background-color: yellow; } 100% { transform: translateY(200px); background-color: purple; } } ``` ```javascript Page({ handleAnimationEnd: function() { const animateBox = this.selectComponent('.animate-box'); animateBox.animate({ classes: 'animation2 2s forwards' }, () => { console.log('第二个动画播放完毕'); }); } }); ``` ### 解释: 1. **定义动画**:`animation1`和`animation2`分别在CSS中定义。 2. **应用动画**:在`.animate-box`元素上应用`animation1`。 3. **监听动画事件**:通过`bindanimationend`绑定`handleAnimationEnd`事件处理函数,在第一个动画结束时触发。 4. **应用第二个动画**:在事件处理函数中,使用`animate`方法应用第二个动画`animation2`。 这样,当第一个动画播放到一半时,第二个动画会自动加载并播放。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值