简体   繁体   中英

jquery background image rotating script doesn't work

I'm writing this script to rotate a background Image every 3 seconds but it doesn't work at all and i'm stumped as to why not.

$(document).ready(function() {

        var inc = 0;
        var bgImages = new Array();
        bgImages.push("Images/backgroundDog-small.jpg");
        bgImages.push("Images/backgroundDog1-small.jpg");
        bgImages.push("Images/backgroundDog2-small.jpg");
        bgImages.push("Images/backgroundDog3-small.jpg");

        setInterval(change, 3000);

        function change() {
            //if we're not at the end of the array
            if (inc < (bgImages.length)) {
                var image = bgImages[inc];
                $('body').css('backgroundImage', image);
                console.log(image);
                inc++;


            //reset the counter inc and go through the array again
            } else {
                inc = 0;
            }
        }
    });

The background-image attribute in CSS doesn't expect just the image URL; you need to write it like you actually would in a stylesheet: url("example.png")

$('body').css('backgroundImage', 'url("'+image+'")');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM