使用javascript减慢后台更改持续时间

时间:2015-05-27 10:12:16

标签: javascript jquery html css

我能够让我的网站标题在一段时间后改变它的背景,但是当它闪烁时它看起来并不好。

Here是该网站。反正有没有改变行动的持续时间?我试图用css动画完成它,但事实证明"背景:"对于某些浏览器,它不会像"background-color:"属性那样工作。无论如何这里是我的代码,你能不能给我一些建议。谢谢!

$(document).ready(function(){
var header = $('.header');

var backgrounds = new Array(
    'url("wp-content/themes/the-best-of-the-old-school/pics/header-bg.jpg")', 'url("wp-content/themes/the-best-of-the-old-school/pics/fire-bg.jpg")'
);

var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background', backgrounds[current]);
}

setInterval(nextBackground, 5000);

header.css('background', backgrounds[0]);

});

2 个答案:

答案 0 :(得分:1)

您可以使用jQuery Animate

替换此行代码

header.css('background', backgrounds[current]);

使用以下

header.animate({opacity: 0}, 'slow', function() {
    $(this)
        .css({'background-image': backgrounds[current]})
        .animate({opacity: 1});
});

查看答案herehere

答案 1 :(得分:0)

您可以在不同的CSS类中定义背景图像:

.bg-0 {
    background: url("wp-content/themes/the-best-of-the-old-school/pics/header-bg.jpg");
}
.bg-1 {
    background: url("wp-content/themes/the-best-of-the-old-school/pics/fire-bg.jpg");
}
...

然后只切换标题上的不同类:

var backgrounds = [1,2,3,4,5,6];

function nextBackground() {
    current++;
    current = current % backgrounds.length;
    header.removeClass("bg-"+(current-1)).addClass("bg-"+current);
}

这将确保所有图像无需进一步加载即可加载。当您第一次切换时,可能所有图像都可用。这将加载页面加载时的所有图像,这意味着即使一个人可能没有足够长的时间来查看所有图像,他们仍会加载它们。

相关问题