Javascript幻灯片循环两次很好,然后出现错误

Javascript slideshow cycles fine twice, then bugs out

本文关键字:很好 然后 错误 两次 循环 幻灯片 Javascript      更新时间:2023-09-26

我按照教程创建了一个简单的javascript幻灯片,但我遇到了一个奇怪的错误。。。前两个周期工作得很好,但一旦计数器重置,幻灯片就会开始快速显示前一张幻灯片,然后尝试在正确的幻灯片中淡出。知道是什么原因造成的吗?

我在一个文件夹中有3个图像(分别命名为Image1.pngImage2.pngImage3.png),用于我的简单幻灯片放映,还有3个div设置如下:

    <div id="SlideshowFeature">
        <div id="counter">
            3
        </div>
        <div class="behind">
            <img src="SlideShow/image1.png" alt="IMAGE" />
        </div>
        <div class="infront">
            <img src="SlideShow/image1.png" alt="IMAGE" />
        </div>
    </div>

我的javascript看起来像这个

var nextImage;
var imagesInShow;
var currentImage;
var currentSrc
var nextSrc
function changeImage() {
    imagesInShow = "3";
    currentImage = $("#counter").html();
    currentImage = parseInt(currentImage);

    if (currentImage == imagesInShow) {
        nextImage = 1;
    }
    else {
        nextImage = currentImage + 1;
    }
    currentSrc = $(".infront img").attr("src");
    nextSrc = "SlideShow/image" + nextImage + ".png";
    $(".behind img").attr("src", currentSrc);
    $(".infront").css("display", "none");
    $(".infront img").attr("src", nextSrc);
    $(".infront").fadeIn(1000);
    $("#counter").html(nextImage);
    setTimeout('changeImage()', 5000);

}
$(document).ready(function () {
    changeImage();
});

编辑:

这里还有我的CSS

#SlideshowFeature
{
text-align:center;
margin: 0 auto;
width:800px;
background: #02183B;
height:300px;
float: left;
overflow:hidden;
display:inline;
}
#SlideshowFeature div
{
    width: 800px;
    height:300px;
    position:absolute;
}
#counter
{
    display:none;
}

问题似乎出现在HTML结构中(而不是JS中):

...
<img src="SlideShow/image1.png" alt="IMAGE" />
...
<img src="SlideShow/image1.png" alt="IMAGE" />
...

我想你是想先放image1.png,然后放image2.png

.infront必须在前面,.behind必须在后面

    .behind {
        z-index: 1;
    }
    .infront {
        z-index: 255;
    }

我还将重新调度逻辑转移到了fadeIn回调:

$(".infront").fadeIn(1000, function(){setTimeout('changeImage()', 2500)});
$("#counter").html(nextImage);
//setTimeout('changeImage()', 2500);

我现在看起来不错。