简体   繁体   中英

Jquery function to change background image every 5 seconds not working

I have the following function in jquery:

window.onload = function() {

    $(function () {
        var images = ["banner.png", "banner2.png"];
        var i = 0;
        setInterval(function () {
            i++;
            if (i == images.length) {
                i = 0;
            }
            $("#banner").fadeOut("slow", function () {
                $(this).css("background", "url(../media/img/" + images[i] + ") no-repeat");
                $(this).fadeIn("slow");
            });
        }, 5000);
    });
}

I want it to change background every 5 seconds, however it changes to a an empty background, here's the CSS code:

#banner{
    position: absolute;
    top: 32px;
    width: 100%;
    background: url(../media/img/banner.png) no-repeat;
    height: 628px;

Just for the record I do have a banner2.png in my file, I don't understand what's wrong

Relative CSS paths can be tricky (this has tripped me up more times than I care to admit)

In a CSS file, the path is relative to that CSS file

When setting it through javascript, it's relative to the HTML file of the page

So, if your folder layout is like

root
|- css
|   |- style.css
|
|- media
|   | - banner.jpg
|   | - banner1.jpg
|
|- index.html

Then the CSS would reference the banner.jpg as ../media/banner.jpg

But when setting the background from javascript in index.html ... the path is ./media/banner.jpg or even media/banner.jpg

So

$(this).css("background", "url(./media/img/" + images[i] + ") no-repeat");

or

$(this).css("background", "url(media/img/" + images[i] + ") no-repeat");

Or (I think a little easier to read - but not available in Internet Explorer) using template strings (ie in backticks ``) - also, just change background-image since the no-repeat is in the original CSS

$(this).css("background-image", `url(media/img/${images[i]})`);

You can even use the " that seem to be not-required, but shown everywhere background-image is documented

$(this).css("background-image", `url("media/img/${images[i]}")`);

Although, I think that is less readable (❁´◡`❁)

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