Js实现缓动动画函数
基于JavaScript的缓动动画函数,用于实现dom元素的多种css属性同时动画效果。它使用定时器实现逐帧动画,支持多个属性同时变化,并在动画完成后执行回调函数。
代码如下:
function animate(obj, json, callback) {
// 参数验证
if (!obj || !json) {
console.error('animate: 缺少必要参数');
return;
}
clearInterval(obj.timer);
var speed, current;
obj.timer = setInterval(function () {
var lock = true;
for (var prop in json) {
if (!json.hasOwnProperty(prop)) continue;
// 获取当前值(兼容IE8)
var computedStyle = obj.currentStyle || window.getComputedStyle(obj, null);
if (prop === 'opacity') {
current = Math.round(parseFloat(computedStyle[prop]) * 100);
} else {
current = parseFloat(computedStyle[prop]);
}
// 处理NaN情况
if (isNaN(current)) {
current = prop === 'opacity' ? 100 : 0;
}
// 缓动计算
speed = (json[prop] - current) / 7;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
// 应用新值
if (prop === 'opacity') {
obj.style[prop] = (current + speed) / 100;
// IE兼容
obj.style.filter = 'alpha(opacity=' + (current + speed) + ')';
} else if (prop === 'zIndex') {
obj.style[prop] = json[prop];
} else {
obj.style[prop] = current + speed + 'px';
}
// 检查是否到达目标
if (Math.abs(json[prop] - current) > Math.abs(speed)) {
lock = false;
}
}
// 所有属性到达目标,停止动画
if (lock) {
clearInterval(obj.timer);
obj.timer = null;
if (typeof callback === 'function') {
callback.call(obj);
}
}
}, 30);
}函数解析
参数:
obj: 要执行动画的DOM元素
json: 包含目标样式属性的对象(如:{left: 200, opacity: 50})
callback: 动画完成后的回调函数(可选)
核心逻辑:
清除旧定时器:防止多个动画冲突
设置新定时器:每30ms执行一次动画帧
属性遍历:对每个目标属性计算当前值和变化速度
缓动计算:使用速度衰减公式实现缓动效果
完成检测:所有属性到达目标值时停止动画
使用场景
1. 元素移动动画
var box = document.getElementById('box');
animate(box, {
left: 300,
top: 200
}, function() {
console.log('移动完成');
});2. 淡入淡出效果
// 淡入
animate(element, {opacity: 100}, function() {
console.log('淡入完成');
});
// 淡出
animate(element, {opacity: 0}, function() {
element.style.display = 'none';
});3. 复杂组合动画
// 同时执行多个属性动画
animate(element, {
width: 400,
height: 300,
opacity: 80,
left: 100
}, function() {
console.log('所有动画完成');
});4. 动画序列
// 链式动画
function animationSequence(element, animations, index) {
index = index || 0;
if (index >= animations.length) return;
var currentAnim = animations[index];
animate(element, currentAnim.props, function() {
if (currentAnim.callback) currentAnim.callback();
animationSequence(element, animations, index + 1);
});
}
// 使用示例
animationSequence(box, [
{props: {left: 200}, callback: function() { console.log('第一步完成'); }},
{props: {top: 150, opacity: 50}, callback: function() { console.log('第二步完成'); }},
{props: {left: 50, opacity: 100}}
]);现代替代方案
对于现代项目,建议使用:
CSS Transitions/Animations - 性能更好
Web Animations api - 原生JS动画API
GSAP - 专业动画库
anime.js - 轻量级动画库
这个animate函数适合学习动画原理或在兼容项目中使用。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!