写一个Javascript方法实现dom元素向上抛出再落下的动画要求动画轨迹是贝塞尔曲线
function animate(element, distance, duration, easingFunction) { let start = null; let currentPosition = 0; const startPosition = element.offsetTop; const endPosition = startPosition - distance;
function step(timestamp) { if (!start) start = timestamp; const timeElapsed = timestamp - start; const progress = Math.min(timeElapsed / duration, 1); const easing = easingFunction(progress); currentPosition = startPosition - (easing * distance); element.style.top = currentPosition + 'px'; if (progress < 1) { window.requestAnimationFrame(step); } else { start = null; window.requestAnimationFrame(fall); } }
function fall(timestamp) { if (!start) start = timestamp; const timeElapsed = timestamp - start; const progress = Math.min(timeElapsed / duration, 1); const easing = easingFunction(progress); currentPosition = endPosition + (easing * distance); element.style.top = currentPosition + 'px'; if (progress < 1) { window.requestAnimationFrame(fall); } else { start = null; } }
window.requestAnimationFrame(step); }
// Example usage: const element = document.getElementById('myElement'); animate(element, 100, 1000, function easeInOutQuart(t) { return t<.5 ? 8tttt : 1-8*(--t)tt*t; }); // The easing function used here is the easeInOutQuart function from https://easings.net/#easeInOutQuart
原文地址: https://www.cveoy.top/t/topic/45r 著作权归作者所有。请勿转载和采集!