我正在使用纯javascript处理fadein和fadeout函数,这里是代码:
(function() {
var fx = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete();
}
}, options.delay || 10);
},
fadeOut: function(element, options) {
var to = 1;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options) {
var to = 0;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.fx = fx;
})()
我使用以下代码激活该功能:
document.getElementById('in').addEventListener('click', function() {
FX.fadeIn(document.getElementById('type'), {
duration: 2000,
});
}, false);
但是当我加载页面时,我的激活码会出错。
有谁知道我做错了什么?
非常感谢你。
答案 0 :(得分:12)
通过一些调整,您的代码应该可以正常工作......
fx
而不是FX
来调用该对象。如果未提供选项,则为所有选项添加默认值(由于options.complete
未定义,您的示例代码会引发错误)。例如:
this.animate({
duration: options.duration || 1000,
...
complete: options.complete || function() { },
...
});
在设置动画之前调整样式(假设使用display: none
隐藏元素而不是opacity: 0
)...示例(适用于fadeIn
):
element.style.opacity = 0;
element.style.visibility = "visible";
element.style.display = "block";
检查是否需要采取任何措施(例如,尽管元素已经可见,但仍可致电fadeIn
):
isVisible: function(element) {
return element.style.display !== "none" &&
element.style.visibility !== "hidden" &&
element.style.opacity !== "0";
}
// In fadeIn:
if (!this.isVisible(element)) {
...
}
以下是带有示例的更正代码:JSFiddle
当然有人可以进一步调整一下,处理一些极端情况(例如,当元素当前正在消失时,如果调用fadeIn
会发生什么?),我很确定它不适用于所有浏览器(旧IE)...但我希望我指出你正确的方向。 :)