【问题标题】:slow down background change duration with javascript使用javascript减慢背景更改持续时间
【发布时间】:2015-08-09 08:40:28
【问题描述】:

我可以让我的网站标题在一定时间后改变它的背景,但它在闪烁时看起来不太好。

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]);

});

【问题讨论】:

  • 你应该在显示current图像时开始预加载current + 1图像,如果闪烁效果是由于加载时间引起的

标签: javascript jquery html css


【解决方案1】:

您可以在不同的 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);
}

这将确保所有图像都可以毫不费力地加载。到您第一次切换时,可能所有图像都将可用。 Ofc 这将在页面加载时加载所有图像,这意味着即使一个人可能没有停留足够长的时间来查看所有图像,但他们仍然会加载它们。

【讨论】:

    【解决方案2】:

    您可以使用jQuery Animate

    替换这行代码

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

    如下

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

    查看答案herehere

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多