js实现变速
实现 JavaScript 变速效果
在 JavaScript 中实现变速效果通常涉及动画、滚动或元素运动的平滑过渡。以下是几种常见的实现方法:
缓动动画(Easing)
缓动函数可以创建变速效果,使动画从慢到快或从快到慢。常见的缓动函数包括线性、二次、三次等。

function easeInOutQuad(t, b, c, d) {
t /= d / 2;
if (t < 1) return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
function animate(element, property, target, duration) {
const start = parseFloat(getComputedStyle(element)[property]);
const change = target - start;
const startTime = performance.now();
function update(time) {
const elapsed = time - startTime;
const progress = Math.min(elapsed / duration, 1);
const value = easeInOutQuad(progress, start, change, 1);
element.style[property] = value + 'px';
if (progress < 1) requestAnimationFrame(update);
}
requestAnimationFrame(update);
}
平滑滚动
实现页面平滑滚动时可以使用变速效果,使滚动速度逐渐变化。
function smoothScroll(target, duration) {
const targetElement = document.querySelector(target);
const targetPosition = targetElement.getBoundingClientRect().top;
const startPosition = window.pageYOffset;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = easeInOutQuad(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
基于时间的动画控制
使用时间作为动画进度的基础,可以实现更精确的变速控制。

function timedAnimation(element, property, target, duration) {
const startValue = parseFloat(getComputedStyle(element)[property]);
const change = target - startValue;
const startTime = Date.now();
function update() {
const currentTime = Date.now();
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = Math.sin(progress * Math.PI / 2); // 正弦缓动
const currentValue = startValue + (change * easedProgress);
element.style[property] = currentValue + 'px';
if (progress < 1) requestAnimationFrame(update);
}
update();
}
使用 CSS 和 JavaScript 结合
通过 JavaScript 动态修改 CSS 的 transition-timing-function 属性,可以实现更复杂的变速效果。
function cssEasingAnimation(element, property, target, duration, easing) {
element.style.transition = `${property} ${duration}ms ${easing}`;
element.style[property] = target;
setTimeout(() => {
element.style.transition = 'none';
}, duration);
}
基于物理的变速
模拟物理效果如重力、弹力等,可以创建更自然的变速运动。
function physicsAnimation(element, property, target) {
const startValue = parseFloat(getComputedStyle(element)[property]);
let velocity = 0;
const stiffness = 0.2;
const damping = 0.5;
function update() {
const currentValue = parseFloat(getComputedStyle(element)[property]);
const displacement = target - currentValue;
const acceleration = displacement * stiffness - velocity * damping;
velocity += acceleration;
element.style[property] = (currentValue + velocity) + 'px';
if (Math.abs(displacement) > 0.1 || Math.abs(velocity) > 0.1) {
requestAnimationFrame(update);
}
}
update();
}
这些方法可以根据具体需求进行调整和组合,实现各种复杂的变速效果。






