// 封装动画函数
function animate(element, target) {
//传 运动的元素 和 运动的距离两个参数
// 通过判断,只允许一个定时器执行
if (element.timeId) {
//element.timeId 让每一个盒子记录自己的timeId
clearInterval(element.timeId);
element.timeId = null;
}
element.timeId = setInterval(move, 5);
function move() {
// 定义每步移动距离
var step = 10;
// 如果当前位置大于目标位置,step应该为负数
var current = element.offsetLeft;
if (current > target) {
step = -Math.abs(step);
}
if (Math.abs(current - target) < Math.abs(step)) {
//清楚定时器
clearInterval(element.timeId);
//设置横坐标为定义的数
element.style.left = target + 'px';
return;
}
current += step;
// style.left获取样式属性,是获取标签内style中的样式属性的值,如果没有该样式属性,则返回空字符串
//box.offsetLeft是只读属性,无法赋值,这里需要同步offsetLeft的值和style.left的值,就是取消Body的margin值
element.style.left = current + 'px';
}
}
网友评论