我有一个简单的脚本,可以淡入淡出一些图像。在我切换到另一个选项卡然后切换回来之前,它工作得非常好。切换回来后似乎运行动画的间隔没有被清除并且animateFading
功能继续运行。
为什么会发生,选项卡切换如何影响脚本?我怎样才能让它正常工作?谢谢!
真实代码:
var img0 = document.getElementById("image0");
var img1 = document.getElementById("image1");
var img2 = document.getElementById("image2");
var imgs = [img0,img1,img2];
var intervalFading;
var intervalAnimate;
var imgThis = 0;
var imgNext = 1;
var fadeIn = 0;
var fadeOut = 1;
var start;
function animateFading() {
fadeIn+=0.1;
fadeOut-=0.1;
imgs[imgThis].style.opacity = fadeOut;
imgs[imgNext].style.opacity = fadeIn;
if (fadeIn >= 1) {
clearInterval(intervalAnimate);
if (imgNext < 2) {
imgNext++;
} else {
imgNext = 0;
}
if (imgThis < 2) {
imgThis++;
} else {
imgThis = 0;
}
fadeIn = 0;
fadeOut = 1;
}
}
function fading() {
intervalAnimate = setInterval(animateFading,50);
}
function startFading() {
start = setInterval(fading, 3000);
}
window.addEventListener('load', startFading);
解决方案:
var startedFading = false;
function startFading() {
if (!startedFading) {
startedFading = true;
startFading = setInterval(fading, 5000);
}
}
function stopFading() {
startedFading = false;
clearInterval(startFading);
}
window.addEventListener('focus', startFading);
window.addEventListener('blur', stopFading);
布尔值用于 Chrome,因为它会触发两次
window.addEventListener('focus', startFading);
&
window.addEventListener('blur', stopFading);