美文网首页
js-元素在X轴上的平移动画

js-元素在X轴上的平移动画

作者: AssertDo | 来源:发表于2019-08-01 11:20 被阅读0次
               //元素在X轴上的平移动画,传入元素和目标位置
                function moveAnimate(element,target){
                    //先清理定时器
                    clearInterval(element.timerId);
                    //给元素添加timerId属性,防止创建多个定时器以至于最后销毁不了
                    element.timerId = window.setInterval(function(){
                        
                        //获取到元素的当前位置 没有px
                        var current = element.offsetLeft;
                        //每次走的步数
                        var step = 10;
                        //判断目标位置是否大于当前位置
                        step = target > current ? step : -step;
                        //移动到目标位置
                        current += step;
                        if(Math.abs(target - current) > Math.abs(step)){
                            element.style.left = current + "px";
                        }else{
                            //销毁定时器
                            window.clearInterval(element.timerId);
                            //让元素走到目标位置
                            element.style.left = target + "px";
                        }
    
                    },20);
                    
                }
    

    相关文章

      网友评论

          本文标题:js-元素在X轴上的平移动画

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