简而言之,jQuery 动画是一种循环计时器,它会在每次计时器滴答时更改一个或多个 CSS 属性。
此外,jQuery 还实现了一种补间算法,该算法会在每个计时器滴答声上进行计算,无论动画是提前还是落后于计划,并进行调整,以便动画始终在指定的准确时间完成。
此外,jQuery 还实现了一个动画队列,以便可以将多个动画链接在一起(前一个动画完成后开始下一个动画)。
此外,jQuery 支持缓动函数,允许您指定非线性动画,根据特定算法在一段时间内改变其速度。
仅供参考,jQuery javascript 源代码是完全可用如果您想了解更多详细信息。这项工作的核心是一个名为的本地函数doAnimation()
,尽管大部分工作是在称为的函数中完成的step
and update
可以通过定义找到jQuery.fx.prototype
.
这是另一个答案,显示了简单的淡入淡出动画在纯 JavaScript 中。
这是一个一般教程关于动画。
您可以看到关于使用计时器进行动画的讨论here.
你可以看看关于补间的讨论here.
这是您的特定动画的 JavaScript 版本:
// node is the DOM element to animate
// prop is the CSS property name to animate
// end is the CSS value to animate to (only supports px units)
// duration is the time of the animation in ms
// fn is an optional callback when the animation is done
// fn is called like this fn(node, arg)
// arg is an optional argument that is passed to the callback
// context is an optional argument that is the this pointer for the function
function animate(node, prop, end, duration, fn, arg, context) {
var stepTime = 20;
var startTime = new Date().getTime();
var start = parseInt(getComputedStyle(node).getPropertyValue(prop), 10);
if (typeof end === "string") {
end = parseInt(end, 10);
}
function step() {
// calc how much time has elapsed
var nextValue, done, portionComplete;
var timeRunning = new Date().getTime() - startTime;
if (timeRunning >= duration) {
nextValue = end;
done = true;
} else {
portionComplete = timeRunning / duration;
nextValue = ((end - start) * portionComplete) + start;
done = false;
}
// set the next value
node.style[prop] = nextValue + "px";
if (!done) {
setTimeout(step, stepTime);
} else {
if (fn) {
context = context || window;
fn.call(context, node, arg);
}
}
}
// start the animation
step();
}
工作演示:http://jsfiddle.net/jfriend00/Mc3xD/
为了简单理解,这并没有实现.stop()
jQuery 示例的一部分,因为这需要一个单独的数据结构来跟踪给定对象上运行的每个动画计时器,这可以在支持的更复杂的版本中看到stop()
: http://jsfiddle.net/jfriend00/mp4Yq/.