菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
492
0

js动画

原创
05/13 14:22
阅读数 36753
<!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>

 

发表评论

0/200
492 点赞
0 评论
收藏