利用動畫延遲(animation-delay)實現複雜動畫

谢勇飞~發表於2024-04-24

<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> :root { --delay:0s; } .box{ width:100px; height:100px; border-radius: 50%; background: red; animation: cartoon 5s linear var(--delay); animation-play-state: paused; animation-fill-mode: none; } @keyframes cartoon { 25%{ transform: translate(0); } 25%{ background:blue; transform: translate(600px) scale(0.3); } 75%{ background:green; transform: translate(900px) scale(0.9); } 100%{ transform: translate(1000px); } } </style> </head> <body> <div class="box"></div> <input type="range" name="hello" id="range" min="0" max="1"step="0.01"> </body> </html> <script> /** * 更新動畫延遲時間以控制動畫進度 * @param {HTMLElement} element - 需要控制動畫的元素 * @param {number} value - 控制值,通常來源於input元素,範圍從0到1 * @param {string} duration - 動畫持續時間,格式為"Xs"或"Xms" */ function updateAnimationDelay(element, value) { const duration = getComputedStyle(element).animationDuration; const delayTime = `-${value * parseFloat(duration)}s`; element.style.setProperty('--delay', delayTime); } const range = document.querySelector('#range') const box = document.querySelector('.box') range.addEventListener('input', (event) => { const v = event.target.value updateAnimationDelay(box, v); }); // 在程式碼載入時手動觸發一次回撥函式 range.dispatchEvent(new Event('input')); </script>

相關文章