【问题标题】:Background-change works only in chrome + $.preload doesn't work背景更改仅适用于 chrome + $.preload 不起作用
【发布时间】:2016-07-19 19:06:03
【问题描述】:

我编写了一个脚本,每 8 秒更改一次背景图像。在 chrome 中一切正常,但在其他浏览器中却不行。 (在 Safari、Edge、IE 9 - 11 和 Mozilla 上测试)。我也有 jQuery 预加载插件,但它实际上并没有预加载图像。控制台没有显示任何错误,所以我不知道为什么它不起作用。 代码:

var c = 1,  
    nimg = $('header .background .img').attr('data-bg'),
    bgpath = $('header .background .img').css('background').match(/"(.*)"/),
    imgpath,
    imgs = [],
    startpath,
    startpoint,
    selector = 'header .background .content .text',
    time = 8000;
if (path[1] == 'diwerf') {
    startpath = '/'+path[1];
} else {
    startpath = '/templates';
};
startpoint = bgpath[1].search(startpath);
bgpath = bgpath[1].slice(startpoint);

for (var g = 1; g <= nimg; g++) {
    imgpath = bgpath.replace(/[0-9]/g, g);

    imgs.push(imgpath);
};

$.preload(imgs);

function removeText() {
    setTimeout(function() {
        $(selector).fadeOut('slow', function() {
            $(this).removeClass('animated').removeAttr('style');
        });
    }, time-600);
}

removeText();

setInterval(function() {
    if (c == nimg) {
        c = 0;
    };
    c++;
    bgpath = bgpath.replace(/[0-9]/g, c);
    $('header .background .img').css('background', 'url('+bgpath+') center center no-repeat');

    setTimeout(function() {
        $(selector+'-'+c).addClass('animated');
    }, 600);

    removeText();
}, time+100);

它没有做任何事情,甚至没有添加“动画”类。

这里可以看到网址:http://www.testing.dw-erfolg.eu/

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery html css google-chrome


    【解决方案1】:

    您使用的是简写 CSS 属性,并非所有浏览器都保证这一点。

    bgpath = $('header .background .img').css('background').match(/"(.*)"/),
    

    您应该使用.css('backgroundImage')

    确保您也更改了第 42 行:

    $('header .background .img').css('backgroundImage', 'url('+bgpath+')');
    

    【讨论】:

    • 您好,感谢您的帮助。另外,你知道为什么 $.preload 不起作用吗?
    • 您在该行之前有一个错误,因此可能会导致浏览器无法访问该部分。进行更改并再次检查。
    • 没用,但没关系。我用了别的东西。还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多