/**
* 动画函数封装
* @param element (object)元素对象
* @param target (int) 目标位置
* @param step (int)步数
* @param time (int)毫秒值
*/
function animate(element, target, step, time) {
// 首先清除定时器,确保多次点击按钮之后只有一个定时器运行
clearInterval(element.timeId);
element.timeId = setInterval(function () {
// 获取当前值
var current = element.offsetLeft;
// 设置步数,判断当前位置是否小于目标位置
step = current < target ? step : -step;
// 每次移动后的距离
current += step;
// 判断当前移动后的距离是否达到目标位置
if (Math.abs(target - current) > Math.abs(step)) {
element.style.left = current + "px";
} else {
// 清除定时器
clearInterval(element.timeId);
element.style.left = target + "px";
}
}, time)
}
JS:动画函数封装
最新推荐文章于 2023-11-18 23:59:25 发布