缓动动画基本封装04(移动方向不限)

1.缓动动画核心思路 : 由快到慢
本次移动距离 = (目标位置 - 当前位置)/10
2.缓动动画特点
(1)需要取整 : 本次移动距离计算是一个除法的过程,会产生小数。而像素一般是整数
(2)没有误差 : 核心公式到了后面,都是1px的移动。
不需要边界检测 : 超过目标位置,清除定时器 并且 元素复位
需要终点检测 : 到达终点, 清除定时器
3.缓动动画封装思路
(1)解决代码冗余 -> 函数
(2)解决 移动距离 不限 -> 函数参数
(3)解决 移动元素 不限 -> 函数参数
(4)解决 移动方向 不限
(5)解决 移动属性 不限 -> 目前只能水平移动, 无法上下移动,无法改变宽高
(6)解决 移动属性数量 不限 -> 目前一次只能改变一个属性
最终动画 : 可以移动任意元素, 任意属性(不限数量) , 还可以移动多次

本小节目标 : 移动方向不限
1.发现问题 : 缓动动画可以 (1)从左往右:没有误差 (2) 和从右往左移动 : 有误差
2.分析问题 :
a. 为什么缓动动画可以自动从右往左 : 核心公式自动根据移动方向得到 正数 | 负数
b. 为什么从右往左有误差
从左往右 : 目标位置 > 当前位置
(1) step = (目标位置-当前位置)/10 正数
(2) (400-391)/10 = 0.9 Math.ceil(0.9) = 1 继续往右移动
从右往左 : 目标位置 < 当前位置
(1) step = (目标位置-当前位置)/10 负数
(2) (400-409)/10 = -0.9 Math.ceil(-0.9) = 0 Math.floor(-0.9) = -1
3.解决误差问题
从左往右移动 : 向上取整
从右往左移动 : 向下取整

var box = document.querySelector(’#box’);//要移动的元素

    //1. 缓动到400
    document.querySelector('#btn1').onclick = function () {
        animationSlow(box,400);
    };

    //2. 缓动到800
    document.querySelector('#btn2').onclick = function () {
        animationSlow(box,800);
    };


    /**
    * @description: 缓动动画
    * @param {type} ele :  要移动的元素
    * @param {type} target : 目标位置
    * @return: 
    */
    function animationSlow(ele,target){
        //1.清除以前的定时器,以本次为准
        clearInterval(ele.timeID);
        //2.开始本次移动
        ele.timeID = setInterval(function(){
            //2.1 获取元素当前位置
            var currentLeft = ele.offsetLeft;
            //2.2 计算本次移动距离 = (目标位置 - 当前位置)/10
            var step = (target - currentLeft)/10;
            //取整 : 从左往右 : step正数 向上取整    从右往左:step负数 向下取整
            step =  step > 0 ? Math.ceil(step) : Math.floor(step);
            //2.3 开始移动
            currentLeft += step;
            ele.style.left = currentLeft + 'px';
            //2.4 终点检测: 到达终点,清除定时器结束运动
            if( currentLeft == target ){
                clearInterval(ele.timeID);
            };
        },20);
    };

猜你喜欢

转载自blog.csdn.net/cxy9999999/article/details/106467551
今日推荐