JavaScript 实现动画效果主要依赖于以下几个基础概念和技术:
setTimeout
或 requestAnimationFrame
)控制动画的时间进度。以下是一个简单的基于 JavaScript 的动画示例,实现了一个元素从左到右移动的效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript 动画示例</title>
<style>
#box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
function animate(element, targetPosition, duration) {
const startPosition = element.offsetLeft;
const distance = targetPosition - startPosition;
let startTime = null;
function step(timestamp) {
if (!startTime) startTime = timestamp;
const progress = timestamp - startTime;
const percentage = Math.min(progress / duration, 1);
element.style.left = startPosition + distance * percentage + 'px';
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
const box = document.getElementById('box');
animate(box, 300, 1000); // 移动到300px位置,持续1秒
</script>
</body>
</html>
requestAnimationFrame
替代 setTimeout
或 setInterval
。通过以上方法和技巧,可以有效地实现和控制 JavaScript 中的动画效果。
领取专属 10元无门槛券
手把手带您无忧上云