我创建了一个脚本,可以在 500 毫秒内为元素的高度设置动画。
计时器工作正常,但我正在努力使高度持续增加。
如何在时间段内平滑地为高度设置动画?此刻它跳了起来。
我想用更聪明的东西替换以下内容:
self.startHeight + 5
我想这与速度和经过的时间有关吗?
https://jsfiddle.net/zrm7xena/1/
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
this.interval = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + 5; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.interval);
}
}, 16); //60FPS
};
animator.animate(document.getElementById('box'));
}());
提前致谢!
Carorus在下面给出了一个很好的答案。我已经更新了我的 jsfiddle,所以你可以看到最终的代码工作:
https://jsfiddle.net/zrm7xena/8/
Typhoon发布了一个与浏览器 FPS 相关的精彩链接:
如何确定在 JavaScript 动画循环中使用的最佳“帧速率”(setInterval 延迟)?
我可能会使用请求动画帧而不是 setInterval:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
大家干杯!