jquery改变图像

时间:2013-04-01 07:26:32

标签: jquery arrays image

我有这个脚本:

<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”,然后跳到数组中的第一个图像然后它的工作正常(第一,第二,第三,又一次......),

为什么会这样?

2 个答案:

答案 0 :(得分:2)

您正在使用第二个数组索引,方法是将索引变量递增currentImage++;将currentImage初始化为-1将会解决您的第一次问题,并且您将得到零索引( first元素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();

答案 1 :(得分: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++;

DEMO HERE