美文网首页
方块动画移动

方块动画移动

作者: 小透明进击战 | 来源:发表于2019-06-09 10:50 被阅读0次
    移动到400px的div
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #dv {
                width: 100px;
                height: 100px;
                position: absolute;
                background-color: #0099cc;
                margin-top: 30px;
    
            }
        </style>
    </head>
    <body>
    <input type="button" value="移动到400米" id="btn1"/>
    <input type="button" value="移动到800米" id="btn2"/>
    <div id="dv"></div>
    <script src="../common.js"></script>
    <script>
        var btnobj1=my$("btn1");
        var btnobj2=my$("btn2");
        var dvobj=my$("dv");
        function move(element, target) {
            //第二个坑,每点一次按钮就出现一个定时器,容易造成越点越快,
           //所以搜先要清理之前的定时器,保证只存在一个定时器。
            clearInterval(element.timeid);
            //timeid之前是一个变量,现在定义为elment的一个属性,这样无论开多少定时器,
           //timeid内存只占一个,不会开辟新的内存空间。
            element.timeid = setInterval(function () {
          //样式中的left在style标签中,外面获取不到。
          //如果left在style属性中,外面可以获取的到。所以采用offsetLeft。
                var current = element.offsetLeft;
                var step = 10;
                step = target - current > 0 ? step : -step;
                //每次移动后的距离
                current += step;
                //第一个坑
                //判断移动后的距离是否到达目标位置
                if (Math.abs(target - current) > Math.abs(step)) {
                    //显示移动后的距离,但是要考虑最后马上到的距离。
                    element.style.left = current + "px";
                } else {
                    //如果距离小于10,就直接到目标点。
                    clearInterval(element.timeid);
                    element.style.left = target + "px";
                }
            }, 20);
        }
    
        btnobj1.onclick=function(){
            move(dvobj,400);
        };
        btnobj2.onclick=function(){
            move(dvobj,800);
    //动画函数编写之前的代码,存在bug。
    //        var timeid=setInterval(function(){
    //            //获取当前的位置
    //            var current=dvobj.offsetLeft;
    //            //设置当前步数
    //            var step=10;
    //            //设置目标位置
    //            current+=step;
    //            if(current<800){
    //                dvobj.style.left=current+"px";
    //            }else{
    //                clearInterval(timeid);
    //            }
    //        },20);
        };
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:方块动画移动

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