1

我有这个脚本:

<script>
var images = [
    "webit.png",
    "analog.png",
    "projectica.png"
];

currentImage = 0;

function ChangeImage()
{
    currentImage++;

    if (currentImage > images.length - 1)
        currentImage = 0;
    $("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")");

    $("#screenImage").fadeOut(500, function() {
        $("#screenImage").attr("src", "images/works/" + images[currentImage]);
        $("#screenImage").fadeIn(500);
    });
    setTimeout(function() {
        ChangeImage();
    }, 5000);
}

ChangeImage();
</script>

当图像第一次改变时,它会跳过图像数组中的第二个图像,到“projectica.png”,然后到数组中的第一个图像,然后它就可以正常工作(第一次,第二次,第三次,再一次第一的..),

为什么会这样?

4

2 回答 2

2

您正在通过currentImage++;初始化 currentImage 来增加索引变量来使用数组的第二个索引,-1这将解决您的第一次问题,并且您将通过以下方式获得零索引(第一个元素currentImage++;

改变

currentImage = 0;

currentImage = -1;

你的代码是

var images = [
    "webit.png",
    "analog.png",
    "projectica.png"
];

currentImage = -1;

function ChangeImage()
{
    currentImage++;

    if (currentImage > images.length - 1)
        currentImage = 0;
    $("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")");

    $("#screenImage").fadeOut(500, function() {
        $("#screenImage").attr("src", "images/works/" + images[currentImage]);
        $("#screenImage").fadeIn(500);
    });
    setTimeout(function() {
        ChangeImage();
    }, 5000);
}

ChangeImage();
于 2013-04-01T07:29:21.233 回答
1

我认为你应该这样做:

if (currentImage > images.length - 1) currentImage = 0;
$("#screenBackImage").css("background-image", "url(images/works/" + images[currentImage] + ")");

$("#screenImage").fadeOut(500, function () {
    $("#screenImage").attr("src", "images/works/" + images[currentImage]);
    $("#screenImage").fadeIn(500);
});

// Increment the currentImage variable here, not in the begining...
currentImage++;

在这里演示

于 2013-04-01T07:30:30.087 回答