美文网首页webAPI
简单移动动画

简单移动动画

作者: 椋椋夜色 | 来源:发表于2019-05-13 21:08 被阅读0次

    <!DOCTYPE html>
    <html lang="zh-CN">

    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> 简单移动动画 </title>

        <style>
            .box {
                width: 100px;
                height: 100px;
                background-color: rgb(255, 12, 12);
                margin-top: 20px;
                position: absolute;
            }
        </style>
    </head>
    
    <body>
        <input type="button" value="移动到400" id="btn">
        <div class="box"></div>
        <script>
            // 找到元素
            var box = document.querySelector('.box');
            // 添加点击事件
            var btn = document.getElementById('btn').onclick = function () {
    
                var timerID = setInterval(function () {
                    // 获取一下当前位置
                    var box1 = box.offsetLeft;
                    // 要用距离 判断是否大于10,大于就走,不大于就直接到目的地
                    if ((400 - box1) > 10) {
                        // 当前位置往前走1步(1步为10像素)
                        box1 += 10;
                        box.style.left = box1 + "px";
                    } else {
                        //距离不够走一步,就直接到目的地
                        box.style.left = 400 + "px";
                    }
    
                    if (box1 == 400) {
                        // 如果到了目的地就停止
                        clearInterval(timerID);
                    }
    
                }, 10);
            }
        </script>
    

    </body>

    </html>

    相关文章

      网友评论

        本文标题:简单移动动画

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