美文网首页
01js匀速运动动画案例

01js匀速运动动画案例

作者: An的杂货铺 | 来源:发表于2019-03-12 10:08 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            .box {
                width: 100px;
                height: 100px;
                background-color: pink;
                position: absolute;
                left: 0;
                top: 100px;
            }
        </style>
    </head>
    <body>
        <button id="btn">move</button>
        <div class="box"></div> 
        <script>
            var btn = document.getElementById('btn');
            var odiv = document.getElementsByTagName('div')[0];
            var timer = null;//初始化一个定时器
            var num = 0;
            // 点击按钮让odiv向右做匀速运动
            btn.onclick = function(){
               clearInterval(timer);//防止重复点击造成定时器的紊乱
               timer = setInterval(move,20);
            }
            function move(){
                num+=5;
                if(num>600){//此处如果是>=600那么实际运动的距离其实是595px
                    clearInterval(timer);
                }else{
                    odiv.style.left = num+'px';
                }
                
            }
        </script>    
    </body>
    </html>
    

    如图


    image.png

    相关文章

      网友评论

          本文标题:01js匀速运动动画案例

          本文链接:https://www.haomeiwen.com/subject/hjqgpqtx.html