定时器应用——封装移动动画函数

moveElement:要移动的节点对象
targetLeft:移动的目标位置

封装匀速移动动画函数

 function moveAnimated(moveElement,targetLeft) {
            // 先清理定时器,防止定时器累加,速度越来越快
            clearInterval(moveElement.timeId);
            //每次的点击操作都只产生一个定时器,定时器的id值存储到一个对象的属性中
            moveElement.timeId=setInterval(function () {
                // 获取div当前left值
                var currentLeft=moveElement.offsetLeft;
                //设置每次移动一次的距离------步数
                var step=7;
                //判断移动的方向
                step=currentLeft<targetLeft?step:-step;
                // 每次移动后的位置
                currentLeft+=step;
                // 判断当前移动后的位置是否达到目标位置
                if(Math.abs(targetLeft-currentLeft)>Math.abs(step)){
                    moveElement.style.left=currentLeft+"px";
                }else{
                    //到达目标位置则清理定时器
                    clearInterval(moveElement.timeId);
                    moveElement.style.left=targetLeft+"px";
                }
            },20)
        }

封装变速移动动画函数

 function moveAnimated(moveElement,targetLeft) {
        // 先清理定时器,防止定时器累加,速度越来越快
        clearInterval(moveElement.timeId);
        //每次的点击操作都只产生一个定时器,定时器的id值存储到一个对象的属性中
        moveElement.timeId=setInterval(function () {
            // 获取div当前left值
            var currentLeft=moveElement.offsetLeft;
            //设置每次移动一次的距离------步数
            var step=(targetLeft-currentLeft)/10;
            // 正数则向上取整,负数则向下取整
            step=step>0?Math.ceil(step):Math.floor(step);
            // 每次移动后的位置
            currentLeft+=step;
            moveElement.style.left=currentLeft+"px";
            if(currentLeft==targetLeft){
                //到达目标位置则清理定时器
                clearInterval(moveElement.timeId);
            }
            //测试代码
            console.log("目标位置:"+targetLeft+",当前位置:"+currentLeft+",移动步数:"+step);
        },20)
    }

猜你喜欢

转载自blog.csdn.net/weixin_39150852/article/details/84941968
今日推荐