js动画

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            #block {
                position: absolute;
                width: 100px;
                height: 100px;
                background-color: red;
                top: 0;
                left: 0;
            }
        </style>
    </head>
    <body>
        <div id="block"></div>
        <script type="text/javascript">
            window.onload = function () {
                // API实现
                const requestAnimationFrameHandle = () => {
                    const element = document.getElementById('block');
                    let start = null;
                    let animate = null;
                    const step = timestamp => {
                        if (!start) start = timestamp;
                        const progress = timestamp - start;
                        element.style.left =
                            Math.min(progress / 10, 500) + 'px';
                        if (progress < 5000) {
                            animate = window.requestAnimationFrame(step);
                        } else {
                            window.cancelAnimationFrame(animate);
                        }
                    };
                    animate = window.requestAnimationFrame(step);
                };
                requestAnimationFrameHandle();
                // 定时器实现
                const timeAnimation = () => {
                    const element = document.getElementById('block');
                    let progress = 0;
                    let timer = setInterval(() => {
                        element.style.left =
                            Math.min(progress / 10, 500) + 'px';
                        progress = progress + 10;
                        if (progress > 5000) {
                            clearInterval(timer);
                            timer = null;
                        }
                    }, 10);
                };
                timeAnimation();
            };
        </script>
    </body>
</html>

 

posted @ 2020-05-14 15:20  流~星~泪  阅读(130)  评论(0编辑  收藏  举报