关于这个主题,有一篇关于粉碎杂志的好文章:
// On button press…
animateLeft(elm, '250px', '500px', function() {
console.log("Done!");
});
// The implementation
function animateLeft(elm, from, to, done) {
// Turn our CSS values into numbers
// We're being lazy and assuming they're in px
from = parseInt(from, 10);
to = parseInt(to, 10);
// Work out the amount we need to move the box
var diff = to - from;
var duration = 3000;
var startTime = performance.now();
// Set initial position
elm.style.transform = 'translate(' + from + 'px, 0)';
function frame(time) {
// How long has the animation been running?
var animTime = time - startTime;
// Are we done?
if (animTime >= duration) {
// It's likely that the last rendered position wasn't the
// final position, so we set it here.
elm.style.transform = 'translate(' + to + 'px, 0)';
done();
}
else {
// What position should the box be in?
var position = from + (animTime / duration * diff);
elm.style.transform = 'translate(' + position + 'px, 0)';
// Request our next frame
requestAnimationFrame(frame);
}
}
// request our first frame
requestAnimationFrame(frame);
}