js动画之requestAnimationFrame回调函数代替setTimeout

继续完善我上一篇博客:https://www.cnblogs.com/duanhuarong/p/12195466.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        * {margin: 0;padding: 0;}
        #div1 {width: 200px;height: 200px;position: absolute;left: 0;background: red;}
    </style>
</head>
<body>
    <div id="div1"></div>
    <script>
        window.onload = function () {
            let Odiv = document.getElementById("div1");
            let disX = 5;
            let disY = 5;
            let x=0;
            let y=0;
            let maxWidth = window.innerWidth - Odiv.offsetWidth-disX;        //浏览器左边界=浏览器宽度-div的宽度-水平速度矢量  
            let maxHeight = window.innerHeight - Odiv.offsetHeight-disY;     //浏览器右边界=浏览器高度-div的高度-垂直速度矢量
            function auto(){
                if(x>=maxWidth)disX*=-1;
                if(y>=maxHeight)disY*=-1;
                if(x<0)disX*=-1;
                if(y<0)disY*=-1;
                x+=disX;
                y+=disY;
                Odiv.style.left=x+'px';
                Odiv.style.top=y+'px';
               //和setTimeout一样,要手动调用才能实现连续动画。
                window.requestAnimationFrame(auto);
            }
            auto();
        }
    </script>
</body>
</html>

 

参考文档:https://www.cnblogs.com/xiaoyulive/p/6690999.html

posted @ 2020-01-15 10:54  飓风吟  阅读(778)  评论(0编辑  收藏  举报