更改div背景jquery [英] Change div Background jquery

查看:104
本文介绍了更改div背景jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定自己在做什么错.我正在尝试使div的背景图像随时间变化.我从此站点获得了jQuery函数,但对我不起作用.任何提示我在做什么错.

I'm not sure what I'm doing wrong. I'm trying to get the background image of my div to change over time. I got the jQuery function from this site but its not working for me. Any clue what I'm doing wrong.

$(window).load(function () {
    var images = ['wave_01.png', 'wave_02.png'];
    var i = 0;

    function changeBackground() {
        $('main').css('background-image', function () {
            if (i >= images.length) {
                i = 0;
            }
            return 'url(' + images[i++] + ')';
        });
    }
    // Call it on the first time
    changeBackground();
    // Set an interval to continue
    setInterval(changeBackground, 3000);
});

HTML

<div class="main"></div>

CSS

.main {
    background-image: url(../images/wave_01.png);
    background-repeat:no-repeat;
    background-size: 100% 40%;
}

推荐答案

您在JavaScript中获取图片的路径是否正确?你有:

Is your path to images correct in your JavaScript ? You have:

var images = ['wave_01.png', 'wave_02.png'];

但是在您的CSS中是:

But in your CSS it's:

background-image: url(../images/wave_01.png);

这表明图像与Javascript位于同一文件夹中.是这样吗? 如果您的项目采用这种结构,则不一定是不正确的,但值得检查.我认为实际上这可能是一个错误,因为它也需要Javascript放在"images"文件夹中才能工作.

This suggests the images are in the same folder as the Javascript. Is that the case ? This isn't necessarily incorrect if your project is structured that way, but worth checking. I think in reality it probably is an error though, as it would need your Javascript to be in "images" folder too to work.

如果CSS和Javascript都在同一个HTML文件中,则使路径相同,即

If your CSS and Javascript are all in the same HTML file, make the paths the same, i.e.

var images = ['../images/wave_01.png', '../images/wave_02.png'];

如果不确定,请尝试使用绝对路径(例如'/images/wave_01.png')代替.

If you're not sure, try both with absolute paths ( e.g. '/images/wave_01.png') instead.

此外,不确定是否只是错字,但选择器$('main')应该绝对是$('.main').

Also, not sure it it's just a typo or not, but the selector $('main') should definitely be $('.main') instead.

这篇关于更改div背景jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆