我尝试使用javascript将背景设为幻灯片,但它无法正常工作。除了第一次在我点击刷新后图像发生变化外,一切都很完美。然而,第一次图像淡出时,它会出现故障,第一个淡出的图像会再次出现,然后再次消失。我该如何解决?这是代码:
//javascript file for the index page
//Create the slide show for the background
var backgroundImgS = "images/background1.JPG", backgroundImg2S =
"images/background2.JPG", backgroundImg3S = "images/background3.JPG";
var backgroundImg = document.getElementById("backgroundImg"), backgroundImg2
= document.getElementById("backgroundImg2");
/*If the background slide show isn't transitioning, transNum increments
every cycle. When transNum gets to a certain number, trans becomes true as
the slide show starts to transition.
transNum is in that case returned to 0, and opacity goes down 10 per cycle
(opacity is the opacity of backgroundImg). When opacity is at 0,
backgroundImg is assigned the src of
backgroundImg2, and backgroundImg's opacity is returned to 100. After that,
backgroundImg2's src is changed the the next image. imgNum determines which
image the main background
image should contain.*/
var transNum = 0, opacity = 100, trans = false, imgNum = 1;
window.setInterval(function(){
//background slideshow
if(!trans) transNum++;//if the slide show isn't transitioning, increment transNum
if(transNum == 100){//if transNum has counted to 80, start the transition of the background image
transNum = 0;
trans = true;
}
if(trans) opacity -= 10;//make the first image less transparent
if(opacity == 0){
trans = false;
if(imgNum > 2) imgNum = 0;
if(imgNum == 0){
backgroundImg.src = backgroundImgS;
backgroundImg2.src = backgroundImg2S;
} else if(imgNum == 1){
backgroundImg.src = backgroundImg2S;
backgroundImg2.src = backgroundImg3S;
} else if(imgNum == 2){
backgroundImg.src = backgroundImg3S;
backgroundImg2.src = backgroundImgS;
}
opacity = 100;
imgNum++;
}
backgroundImg.style.opacity = opacity / 100 + "";
backgroundImg.style.filter = "alpha(opacity=" + opacity + ")";
答案 0 :(得分:0)
我不能说这会解决所有问题,但您可能应该使用图像onload
事件处理程序来确保您的图像(异步加载)已完全加载并呈现在对它们施加效果之前。