动画核心思路 : 给元素一个速度 = px/ms (开启定时器,间隔时间移动单位距离)
目前代码存在的问题
1. 代码冗余 ->函数
2. 移动距离不限 ->函数参数
3. 移动元素不限 ->函数参数
4. 移动方向不限 -> 可以从左往右移动,也可以从右往左
5. 如果想要改变元素的位置,前提是这个元素要有定位
1.发现问题 : 元素只能从左往右移动,不能从右往左移动
2.分析问题
从左往右移动, 目标位置 > 当前位置 (1)currentLeft += 10 (2)边界检测 if(current>=target)
从右往左移动, 目标位置 < 当前位置 (1)currentLeft -= 10 (2)边界检测 if(current<=target)
3.解决问题 : 判断移动方向
var box = document.querySelector('#box');//目标盒子
//1.点击按钮:目标盒子动画移动到800px
document.querySelector('#btn1').onclick = function () {
animationMove(box, 800);
};
//2.点击按钮:目标盒子移动到400
document.querySelector('#btn2').onclick = function () {
animationMove(box, 400);
};
/**
* @description: 匀速动画封装
* @param {type} ele 要移动的元素
* @param {type} target 目标位置
* @return:
*/
function animationMove(ele, target) {
//1. 先清理以前的定时器,以本次为准
clearInterval(ele.timeID);
//2.开始本次移动
ele.timeID = setInterval(function () {
//1.获取当前位置
var currentLeft = ele.offsetLeft;
//2.开始移动 : 使用一个布尔类型变量表示移动方向 true:从左往右 false:从右往左
var isLeft = target >= currentLeft ? true : false;
//true : currentLeft += 10; false: currentLeft -= 10
isLeft ? currentLeft += 10 : currentLeft -= 10;
ele.style.left = currentLeft + 'px';
//3.边界检测
if (isLeft ? currentLeft >= target : currentLeft <= target) {
//(1)清除定时器
clearInterval(ele.timeID);
//(2)元素复位
ele.style.left = target + 'px';
};
}, 20);
};