利用动画延迟(animation-delay)实现复杂动画


<!
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>

 

posted @ 2024-04-24 16:16  谢勇飞~  阅读(39)  评论(0编辑  收藏  举报