每15秒更换一次背景图像

时间:2014-03-23 16:59:24

标签: javascript html css

您好,
我有一个页面,背景是我在css文件中设置的背景。我想在15秒内改变迭代。
我有2张图片:1.jpg2.jpg。我的CSS看起来像这样

.slide1 {
    max-width: 100%;
    background-attachment: fixed;
    width:100%;
    height: 100%;
    padding-top: 3em;
    position: relative;
    background-color: #FFFFFF;
    background-image: url('billede/1.jpg');
    background-size: auto 70%;
    color:#FFFFFF;
    background-repeat:no-repeat;
    background-position:bottom center;
    margin: 0;
}

这就是背景改变的原因:

<script>
    var arrayOfImages = new Array("billede/green/1.jpg","billede/green/2.jpg");

    $(arrayOfImages).each(function () {
    $('<img />').attr('src',this).appendTo('body').hide;
    });

    setInterval(function(){$(".slide3").css("background-image", "url('billede/green/" + parseInt((Math.random()*2)+1) + ".jpg')");},10000);
</script>

但是现在当它改变图片时,当我开始滚动背景显示时它会显示白色背景。如果没有显示白色背景,我该怎么做才能改变背景?

2 个答案:

答案 0 :(得分:1)

您可以使用Simple HTML和CSS执行此操作。

创建一个HTML Div,每个div设置一个Image Background CSS的类

<div class="x a"></div>
<div class="x b"></div>
<div class="x c"></div>

将尺寸设置为100%,将z-index设置为您喜欢的位置 CSS:

.x {
  background-image:url(image file);
  display: inline-block;
  animation: fade 1s forwards;
  -webkit-animation: fade 1s forwards;
  -moz-animation: fade 1s forwards;
  -o-animation: fade 1s forwards;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  -moz-animation-iteration-count: infinite;  
  -o-animation-iteration-count: infinite;
}


.b 
{
  background-image:url(image file);
    animation: fade 2s forwards;
  -webkit-animation: fade 2s forwards;
  -moz-animation: fade 2s forwards;
  -o-animation: fade 2s forwards;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  -moz-animation-iteration-count: infinite;  
  -o-animation-iteration-count: infinite;
}
.c 
{
  background-image:url(image file);
    animation: fade 3s forwards;
  -webkit-animation: fade 3s forwards;
  -moz-animation: fade 3s forwards;
  -o-animation: fade 3s forwards;
  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  -moz-animation-iteration-count: infinite;  
  -o-animation-iteration-count: infinite;
}


@keyframes fade {
0%   {opacity:0;}
50%   {opacity:1;}
100% {opacity:0;}
}

@-webkit-keyframes fade {
0%   {opacity:0;}
50%   {opacity:1;}
100% {opacity:0;}
}

@-moz-keyframes fade {
0%   {opacity:0;}
50%   {opacity:1;}
100% {opacity:0;}
}

@-o-keyframes fade {
0%   {opacity:0;}
50%   {opacity:1;}
100% {opacity:0;}
}

答案 1 :(得分:0)

这可能是因为加载新的背景图片需要一些时间。要立即显示新背景,您需要预加载它。

请参阅此问题以获得一个好方法: JavaScript Preloading Images