RequestAnimationFrame

645 阅读1分钟
  • RequestAnimationFrame接收一个函数,在函数内部再调用RequestAnimationFrame
<!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>Document</title>
</head>
<style>
    .box {
        width: 100px;
        height: 100px;
        background: pink;
        position: relative;
    }
</style>
<body>
    <div class="box"></div>
</body>
<script>
    let start = new Date().getTime()
    let box = document.getElementsByClassName('box')[0]
    function move() {
        let end = new Date().getTime()
        box.style.marginLeft = `${(end - start) / 20}px`
        window.requestAnimationFrame(move)
    }
    move()
</script>
</html>