简体   繁体   English

Jquery 函数每 5 秒更改一次背景图像不起作用

[英]Jquery function to change background image every 5 seconds not working

I have the following function in jquery:我在 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:我希望它每 5 秒更改一次背景,但是它更改为空背景,这是 CSS 代码:

#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只是为了记录,我的文件中有一个 banner2.png,我不明白出了什么问题

Relative CSS paths can be tricky (this has tripped me up more times than I care to admit)相对 CSS 路径可能很棘手(这让我绊倒的次数比我愿意承认的要多)

In a CSS file, the path is relative to that CSS file在 CSS 文件中,路径是相对于该 CSS 文件的

When setting it through javascript, it's relative to the HTML file of the page通过javascript设置时,相对于页面的HTML文件

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然后 CSS 会将 banner.jpg 引用为../media/banner.jpg

But when setting the background from javascript in index.html ... the path is ./media/banner.jpg or even media/banner.jpg但是当在 index.html 中从 javascript 设置背景时......路径是./media/banner.jpg甚至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或者(我认为更容易阅读 - 但在 Internet Explorer 中不可用)使用模板字符串(即在反引号中``) - 另外,只需更改background-image因为原始 CSS 中no-repeat

$(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您甚至可以使用"似乎不是必需的,但在记录background-image任何地方都显示

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

Although, I think that is less readable (❁´◡`❁)虽然,我认为这不太可读(❁´◡`❁)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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