写一个左右移动的封装函数

/**1.匀速动画
 * @param obj:要移动的元素
 * @param target:要移动的目标距离
 */
function animationMove ( obj,target ) {
    //1.清除之前的定时器,以本次移动为准
    clearInterval(obj.timeID);
    //2.开始本次移动
    obj.timeID = setInterval(function (  ) {
        //2.1 先获取元素当前位置
        var currentLeft = obj.offsetLeft;
        //2.2 开始移动
        var isLeft = target>currentLeft?true:false;//判断移动方向
        isLeft?currentLeft+=10:currentLeft-=10;//根据移动方向开始移动
        obj.style.left = currentLeft + 'px';
        //2.3 边界检测
        if (isLeft?currentLeft>=target:currentLeft<= target){
            //(1)清除定时器
            clearInterval(obj.timeID);
            //(2)元素复位
            obj.style.left = target + 'px';
        }
    },20)

}

猜你喜欢

转载自blog.csdn.net/xiaodi520520/article/details/82966486