【问题标题】:Using JS how can I get the animation end value in the documents timeline使用 JS 如何在文档时间轴中获取动画结束值
【发布时间】:2021-11-21 06:09:09
【问题描述】:

我有一个包含多个 CSS 动画的文档,我需要根据屏幕截图获取在 chrome 开发工具(动画时间线)中可以看到的总运行长度

我想了几种方法,但不确定哪种方法 1. 最准确,2. 最有效

PS CSS 动画类是在加载时动态添加的,因此有时可能会更长,有时会更短

仅供参考,我考虑过使用 JS document.getAnimations() 来获取数组,但不确定 从那里去哪里,因为它们都有相似之处:

数组:

开始时间和当前时间

最终总值:

【问题讨论】:

    标签: javascript css animation timeline


    【解决方案1】:

    我认为您可以使用animationstartanimationend 事件的组合来获得它。这是MDN's example 的修改版本,这里使用了我们随机启动动画的两个不同元素:

    const activeElements = new Map();
    
    function handleAnimationStart({target}) {
        const now = Date.now();
        console.log(`Started on ${target.getAttribute("data-label")} at ${now}`);
        activeElements.set(target, now);
    }
    
    function handleAnimationEnd({target}) {
        const now = Date.now();
        const start = activeElements.get(target);
        if (typeof start === "number") {
            activeElements.delete(target);
            console.log(`Ended on ${target.getAttribute("data-label")} at ${now}, duration = ${now - start}`);
        }
    }
    
    function startAnimation(element) {
        element.classList.toggle("active");
        element.addEventListener("animationstart", handleAnimationStart);
        element.addEventListener("animationend", handleAnimationEnd);
    }
    
    const elements = document.querySelectorAll("p.animation");
    setTimeout(() => {
        startAnimation(elements[0]);
    }, Math.floor(Math.random() * 1000));
    setTimeout(() => {
        startAnimation(elements[1]);
    }, Math.floor(Math.random() * 2000));
    .container {
        height: 3rem;
    }
    
    .event-log {
        width: 25rem;
        height: 2rem;
        border: 1px solid black;
        margin: 0.2rem;
        padding: 0.2rem;
    }
    
    .animation.active {
        animation-duration: 2s;
        animation-name: slidein;
    }
    
    @keyframes slidein {
        from {
            transform: translateX(100%) scaleX(3);
        }
        to {
            transform: translateX(0) scaleX(1);
        }
    }
    <div class="animation-example">
        <div class="container">
            <p class="animation" data-label="0">You chose a cold night to visit our planet.</p>
        </div>
        <div class="container">
            <p class="animation" data-label="1">You chose a cold night to visit our planet.</p>
        </div>
    </div>

    【讨论】:

    • 感谢 T.J!,虽然它很长,但这是一个开始,我会尝试并回帖
    • 经过测试,它确实有效,我想我不想等到动画结束才能获得“结束值”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-08-24
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多