簡體   English   中英

CSS & Javascript 手動關鍵幀 Animation

[英]CSS & Javascript Manual Keyframe Animation

假設我在 css 中定義了一個 animation,如下所示:

@keyframes my-animation {
    0% {
        // effect here
    }

    ...

    100% {
        // effect here
    }
}

我可以像這樣在 div 中使用它:

#container {
    animation: my-animation 10s linear ;
}

有什么辦法可以使用 javascript 以編程方式隨時設置 animation 的百分比嗎? 類似的東西:

function() {
    let container = document.getElementById('container');
    while (some condition && container.percentage < 100) {
        container.percentage += 10;  // Here I would like to set the animation percentage to one of the percentages defined in the keyframe animation
    }
}

這樣我就不必事先明確設置 animation 的持續時間,因為它在運行時是未知的。 我應該補充一點,我知道目前無法檢索 animation 的百分比值,但也許有辦法操縱它?

編輯:據我從 lupz 的評論中了解到:

.animation0 { /* 0% */

    }

.animation10 { /* 10% */

    }

...

.animation100 { /* 100% */

    }

然后我可以將元素的 class 更改為我需要的任何百分比。

你可以通過 JS animation API - Element.animate() ,然后你可以直接通過 JS 控制百分比( offset屬性):

 const container = document.querySelector('.container'); const animate = (offset = 1) => { const height = container.getBoundingClientRect().height; const animation = container.animate([ { transform: 'translateY(0px)', offset: 0 }, { transform: `translateY(calc(100vh - ${height}px))`, offset } ], { duration: 1000, }); if(offset > 0) { animation.finished.then(() => animate(offset - 0.1)); } }; animate();
 html, body { margin: 0; }.container { width: 100px; height: 100px; background: silver; }
 <div class="container"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM