function move(obj, property, step, target, callback) {
clearInterval(obj.t);
//根据起点和终点直接的关系,判别速度的正负
step = parseFloat(getStyle(obj, property)) > target ? -step : step;
//将定时器编号保存在对象的自定义属性上
obj.t = setInterval(function () {
var speed = parseFloat(getComputedStyle(obj)[property]) + step;
//临界值判断
if ((step > 0 && speed >= target) || (step < 0 && speed <= target)) { //终点
clearInterval(obj.t);
speed = target;
if (callback) //动画完成的回调函数
callback()
}
obj.style[property] = speed + 'px'
})
}
function getStyle(obj, property) {
if ("getComputedStyle" in window) {
return window.getComputedStyle(obj)[property];
}
return obj.currentStyle[property]
}
关于匀速运动,变速运动,位置移动...例如轮播,放大镜效果封装
最新推荐文章于 2026-01-06 15:22:38 发布
该博客探讨了如何使用JavaScript实现平滑动画,通过`setInterval`和速度调整来控制元素移动,并在到达目标位置时调用回调函数。同时,介绍了`getComputedStyle`方法用于获取元素的实时样式信息,确保动画过程中的精准控制。
185





