问题:在幻灯片放映中,下面的淡入淡出功能一直调用淡入/淡出功能,请JsFiddle运行大约十秒钟才能看到问题。在IE中不起作用,不要让jsfiddle运行太长时间,它可能会使浏览器崩溃!
JsFiddle:http://jsfiddle.net/HdYmH/
详细信息(对于那些感兴趣的人):嗨,很抱歉用这么大的代码块发布问题。我还在学习javascript,并试图弄清楚如何制作幻灯片。我知道那里有很多js幻灯片,但我想把它想象成一种学习经历。因此请注意,此代码的某些部分非常糟糕。问题可能与幻灯片的changeSlide()方法有关。
我使用firebug来找出几秒后最明显被调用的方法fadeOut将被称为20k +次:|
// Generic fade function that fades in or out
function fade(pElem, pStartOpac, pEndOpac, fps, sec) {
if ((typeof (pElem) !== "string") || (typeof (pStartOpac) !== "number")
|| (typeof (pEndOpac) !== "number") || (typeof (fps) !== "number")
|| (typeof (sec) !== "number")) {
console.log("Parameters incorrect format has to be (string) Element Id, (double) Starting Opacity, (double) End Opacity, (integer) frames per second, (integer) seconds to run");
return;
}
// The CSS opacity property only works from 1 to 0
if (pStartOpac < 0) {
pStartOpace = 0;
}
if (pStartOpac > 1) {
pStartOpac = 1;
}
if (pEndOpac < 0) {
pEndOpac = 0;
}
if (pEndOpac > 1) {
pEndOpac = 1;
}
// Stop the fps from going over 60 or under 1 (The eye will barely notice
// improvements above 60fps and fractional fps are not supported)
if (fps > 60) {
fps = 60;
}
if (fps < 1) {
fps = 1;
}
var totalFrames = (fps * sec);
var opacityChangePerSecond = (Math.abs(pStartOpac - pEndOpac) / sec);
var opacityChangePerFrame = (opacityChangePerSecond / fps);
var timeOutInterval = 1000 * (1 / fps);
// console.log("totalFrames: "+totalFrames);
// console.log("Opacity change per second: " + opacityChangePerSecond);
// console.log("Opacity change per frame: " + opacityChangePerFrame);
// console.log("Time out interval: " + timeOutInterval + " milliseconds");
var opacity = pStartOpac;
var timeoutVar;
var elemId = document.getElementById(pElem);
elemId.style.opacity = opacity;
if (pStartOpac < pEndOpac) {
fadeIn();
return;
} else {
fadeOut();
return;
}
function fadeIn() {
opacity = opacity + opacityChangePerFrame;
if (opacity > pEndOpac) {
clearTimeout(timeoutVar);
return;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeIn, timeOutInterval);
return;
}
function fadeOut() {
if (opacity < pEndOpac) {
clearTimeout(timeoutVar);
return;
}
opacity = opacity - opacityChangePerFrame;
if (opacity < 0) {
opacity = 0;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeOut, timeOutInterval);
return;
}
}
答案 0 :(得分:0)
遇到问题:当不透明度变为&lt; 0时,将其设置为0,然后执行:if (opacity < pEndOpac)
。 pEndOpac为0,因此0 <0的计算结果为false,永远不会清除超时。解决方案是if (opacity <= pEndOpac)
:
function fadeIn() {
opacity = opacity + opacityChangePerFrame;
if (opacity >= pEndOpac) {
clearTimeout(timeoutVar);
return;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeIn, timeOutInterval);
return;
}
function fadeOut() {
if (opacity <= pEndOpac) {
clearTimeout(timeoutVar);
return;
}
opacity = opacity - opacityChangePerFrame;
if (opacity < 0) {
opacity = 0;
}
elemId.style.opacity = opacity;
timeoutVar = setTimeout(fadeOut, timeOutInterval);
return;
}