requestAnimationFrame(callback)允许你在每一帧执行一次回调,这对于制作动画是非常适合的
不多说,直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moving Box</title>
</head>
<body>
<div style="width: 50px; height: 50px; border-radius: 50%; background-color: red;"></div>
<script>
const ball = document.querySelector("div");
let x = 0;
let raf = 0;
function move() {
ball.style.transform = `translateX(${x++}px)`
// 必须要在回调函数中再次调用requestAnimationFrame,否则回调函数只会执行一次,而不是每一帧执行一次
raf = requestAnimationFrame(move);
// 取消动画使用cancelAnimationFrame(requestID)
if(x > 400) cancelAnimationFrame(raf);
}
raf = requestAnimationFrame(move);
</script>
</body>
</html>