我正在为 HTMLElement 编写一个 fadeIn 函数,动画可以工作,但目前有点不稳定。它所做的是将淡入动画从 0 不透明度设置为 1,它还使用 requestFrameAnimation 在一段时间内进行动画处理,这就是为什么它可能如此不稳定,有人可以帮助我让我的动画运行得更流畅吗?示例位于 codepen.io看看标题 fadeIn 就明白我的意思了
fadeIn: function(duration) {
var el = this.$el,
duration,
end = 0;
el.style.opacity = 0;
el.style.display = "block";
var step = function() {
var current = +new Date(),
remaining = end - current;
if(remaining < 60) {
if(el) {
end = current + duration;
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
}
} else {
return;
}
}
requestAnimationFrame(step);
};
step();
},
最佳答案
最流畅的方法是使用 CSS 过渡。但如果你想使用纯 Javascript,你可以这样做
function fadeIn(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.min(1, dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
function fadeOut(dom, duration) {
let start = null;
const step = (end) => {
if (start === null) start = end;
let dt = end - start;
dom.style.opacity = Math.max(0, 1 - dt / duration);
if (dt < duration) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
fadeIn(document.getElementById('your_dom'), 2000);
关于javascript - requestFrameAnimation 使用持续时间时断断续续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718588/