原生JS封装变速移动函数

思想:如果当前位置为now,目标距离为aim,那么每次移动的距离step为(aim-now)/10,如果step大于0,则想上取整,step=Math.ceil(step);反之则向下取整,step=Math.floor(step);
代码如下:

//变速移动函数封装
function movecs(ele,aim){
    //清除定时器
    clearInterval(ele.changespead);

    ele.changespead=setInterval(function() {
        //获取当前位置
        var now = ele.offsetLeft;
        //设置每次移动的单位距离
        var step = (aim - now) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);

        //当前位置改变
        now += step;

        if (Math.abs(now - aim) > Math.abs(step)) {
            ele.style.left = now + 'px';
        }
        else {
            ele.style.left = aim + 'px';
        }
    },20);
}

猜你喜欢

转载自blog.csdn.net/qq_41557320/article/details/83061149
今日推荐