JavaScript 控制动画效果主要通过以下几种方式实现:
setInterval 或 requestAnimationFrame)不断更新元素的位置或样式,从而实现动画效果。@keyframes 规则定义动画序列,然后通过 JavaScript 控制元素的类名切换来触发动画。以下是一个简单的基于 requestAnimationFrame 的平移动画示例:
const box = document.getElementById('box');
let start = null;
const duration = 2000; // 动画持续时间2秒
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const percentage = Math.min(progress / duration, 1);
box.style.transform = `translateX(${percentage * 300}px)`;
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);requestAnimationFrame 而不是 setInterval。transform 和 opacity 属性)。setTimeout 结合动画时长来预估结束时间,或者监听动画结束事件(如 CSS 动画的 animationend)。通过上述方法,可以有效地使用 JavaScript 控制各种复杂的动画效果,提升用户体验。
没有搜到相关的文章