set backgroundPosition and setInterval

set backgroundPosition and setInterval

本文关键字:setInterval and backgroundPosition set      更新时间:2023-09-26

所以我做了一个代码

function slide()
{
    var x=1;
    while (x<=512) 
    {
        document.getElementById("slide").style.backgroundPosition = x+"px 0px";
        x++;
    }
}

JSFIDDLE

我想从backgroundPosition - 0转换到backgroundPosition 512。上面的代码立即从0变为512,我想让它像1<100ms中断>,2,3。。。
我尝试将x++更改为setTimeout(function(){x++), 100),但它没有任何作用。

使用setTimeout()并调用函数:

function slide(x) 
{
    if(x==undefined) var x = 1;
    if(x >= 512) return;
    document.getElementById("slide").style.backgroundPosition = x+"px 0px";
    x++;
    setTimeout(function() {
        // recall function and add other code if you want.
        slide(x);
    }, 100);
}
slide();