切换图像

时间:2014-12-17 16:21:55

标签: javascript jquery html css

我想做的只是每隔x个时间间隔切换DIV的背景图像。

这就是我现在所拥有的:

// Object of Background images per make
var bs = {
    "time": 2000,
        "url": {
        "BMW": ["url('img/cars/bmw/1.jpg')", "url('img/cars/bmw/.jpg')", "url('img/cars/bmw/3.jpg')"],
            "Audi": ["url('img/cars/audi/1.jpg')", "url('img/cars/audi/2.jpg')", "url('img/cars/audi/3.jpg')"],
            "GMC": ["url('img/cars/gmc/1.jpg')", "url('img/cars/gmc/2.jpg')", "url('img/cars/gmc/3.jpg')"]
    }
    //ect...
};
var Slider = $("#Slider"); // DIV element
function Slide(car) {
    var sLength = bs.url[car].length; // array # of pictures available
    Slider.css({
        "background": bs.url[car][index], // ?? here how do you auto increment & restart cycle
        "background-position": "center",
            "background-attachment": "fixed",
            "background-size": "cover"
    });
    setInterval() // here call Slide & ++ index ?
}
$(document).ready(function () {
    Slide("BMW");
});

1 个答案:

答案 0 :(得分:0)

余数运算符非常适用于包装诸如index之类的内容:

index = (index + 1) % length

...其中length是您索引的长度(假设从0开始编制索引)。

因此,您的Slide函数可以执行以下操作:

function Slide(car) {
    var urls = bs.url[car];
    var index = 0;

    function run() {
        Slider.css({
            "background": urls[index],
            "background-position": "center",
            "background-attachment" : "fixed",
            "background-size" : "cover"
        });
        index = (index + 1) % urls.length;
    }    

    run();
    setInterval(run, bs.time);
}