JavaScript 控制动画效果主要通过以下几种方式:
setTimeout 和 setInterval,用于在指定时间后执行代码或周期性地执行代码。<animate> 元素或 JavaScript 来控制 SVG 图形的动画。requestAnimationFrame 可以确保动画在最佳时机执行,提高性能。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation Example</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
const box = document.getElementById('box');
let start;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
box.style.left = Math.min(progress / 10, 200) + 'px';
if (progress < 2000) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
</script>
</body>
</html>原因:
解决方法:
requestAnimationFrame 替代 setTimeout 或 setInterval。原因:
解决方法:
transform 和 opacity 属性,这些属性通常不会触发重排。translate3d 或 will-change。通过以上方法,可以有效控制和优化 JavaScript 中的动画效果,提升用户体验。