css中animation-play-state的使用

之前在网易云音乐移动端上看到过这样一个效果,进入播放页后,歌词上方的图片会随着音乐播放而旋转,并且歌曲暂停也会停止旋转,刚开始做类似效果的时候是通过增删对应激活类的方式来控制旋转的,这样的确能控制旋转,但有一个弊端,那就是停止动画以后,图片会跳到刚开始的模样而不是停止时的状态,这时,开始动画以后图片又会重新开始旋转而不是以停止时的状态开始。后来知道了可以用animation-play-state来控制动画。
MDN中是这样描述的:animation-play-state CSS 属性定义一个动画是否运行或者暂停。可以通过查询它来确定动画是否正在运行。另外,它的值可以被设置为暂停和恢复的动画的重放。恢复一个已暂停的动画,将从它开始暂停的时候,而不是从动画序列的起点开始在动画。

借此做一个简单的DEMO:
html

<div class="container">
        <div class="circleBox">
            <div class="top"></div>
        </div>

        <button class="start">开始旋转</button>
        <button class="pause">停止旋转</button>
    </div>

css

 * {
            margin: 0;
            padding: 0;
        }

        .circleBox {
            width: 100vw;
            height: 50vh;
            display: flex;
            justify-content: center
        }

        .top {
            margin-top: 5vw;
            width: 20vw;
            height: 20vw;
            background-color: aqua;
            animation: circle 10s infinite linear;
        }

        @keyframes circle {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

js

        const topNode = document.querySelector('.top');
        const start = document.querySelector('.start');
        const pause = document.querySelector('.pause');

        start.addEventListener('click', () => {
            // 开始动画
            topNode.style.animationPlayState = 'running';

        });

        pause.addEventListener('click', () => {
            // 停止动画
            topNode.style.animationPlayState = 'paused';
        });
posted @   隐形的喷火龙  阅读(221)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示