美文网首页
变速动画封装函数

变速动画封装函数

作者: 小透明进击战 | 来源:发表于2019-06-11 19:04 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #dv {
            width: 200px;
            height: 100px;
            background-color: khaki;
            margin-top: 20px;
            position: absolute;
            top: 20px;
            left: 0;
        }
    </style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1"/>
<input type="button" value="移动到800px" id="btn2"/>
<div id="dv">
</div>
<script src="../common.js"></script>
<script>
    function changeMove(element,target){
        //首先清理定时器
        clearInterval(element.timeid);
        element.timeid=setInterval(function(){
            //获取当前位置
            var current=element.offsetLeft;
            //设置移动步数
            var step=(target-current)/10;
            //如果步数是正数向上取整,如果是负数,向下取整
            step=step>0?Math.ceil(step):Math.floor(step);
            //移动公式
            current+=step;
            element.style.left =current+"px";
            //如果到目的地清理定时器
            if(current==target){
                clearInterval(element.timeid);
            }
            //添加测试代码
            console.log(current+"px=============="+target+"px============="+step+"px");
        },50);

    }
    my$("btn1").onclick=function(){
        changeMove(my$("dv"),400);
    };
    my$("btn2").onclick=function(){
        changeMove(my$("dv"),800);
    };

</script>

</body>
</html>
变速动画.png

相关文章

网友评论

      本文标题:变速动画封装函数

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