简单的jquery .css背景更改图像与延迟

时间:2014-03-10 13:43:54

标签: javascript jquery

我想在我的welcome_box div中使用jquery按时更改背景。

<div class="welcome_box">
        <p>test</p>
        <small>text</small>
    </div>
</div>

我不需要点击或任何只是自动淡入淡出4个图像,每个图像延迟5秒淡出

我找不到简单的代码,任何人都可以帮我这个吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

试试这个

var i=0;
setInterval(function(){

 $('.welcome_box').css("background-image","url('images/pic"+i+".jpg')");
 $('.welcome_box').fadeToggle();
 i++;
 if(i==4)
 {
    i=0;
}
},5000);

保持像pic1,pic2..etc这样的图像名称

答案 1 :(得分:0)

您的标记无效。试试这个

<div class="welcome_box">
    <div>
        <p>test</p>
        <small>text</small>
    </div>
</div>

现在您可以使用CSS或Javascript实现此目的。对于CSS,您可以使用关键帧动画。您可能需要使用百分比和时间。我想5s x 4图像,所以我放了20s,但我不确定你是否想要在每张图像上停留更长时间并进行过渡5s。

.welcome_box div
{
animation: myfirst 20s;
-webkit-animation: myfirst 20s; /* Safari and Chrome */
}

@keyframes myfirst
{
0%   {background: url(image_1) 0 0 no-repeat; opacity:1;}
9%  {background: url(image_1) 0 0 no-repeat; opacity:0;}
18%  {background: url(image_2) 0 0 no-repeat; opacity:0;}
36%  {background: url(image_2) 0 0 no-repeat; opacity:1;}
45%  {background: url(image_2) 0 0 no-repeat; opacity:0;}
54% {background: url(image_3) 0 0 no-repeat; opacity:0;}
63% {background: url(image_3) 0 0 no-repeat; opacity:1;}
72%  {background: url(image_3) 0 0 no-repeat; opacity:0;}
81%  {background: url(image_4) 0 0 no-repeat; opacity:0;}
90% {background: url(image_4) 0 0 no-repeat; opacity:1;}
99% {background: url(image_4) 0 0 no-repeat; opacity:0;}
}

@-webkit-keyframes myfirst /* Safari and Chrome */
{
0%   {background: url(image_1) 0 0 no-repeat; opacity:1;}
9%  {background: url(image_1) 0 0 no-repeat; opacity:0;}
18%  {background: url(image_2) 0 0 no-repeat; opacity:0;}
36%  {background: url(image_2) 0 0 no-repeat; opacity:1;}
45%  {background: url(image_2) 0 0 no-repeat; opacity:0;}
54% {background: url(image_3) 0 0 no-repeat; opacity:0;}
63% {background: url(image_3) 0 0 no-repeat; opacity:1;}
72%  {background: url(image_3) 0 0 no-repeat; opacity:0;}
81%  {background: url(image_4) 0 0 no-repeat; opacity:0;}
90% {background: url(image_4) 0 0 no-repeat; opacity:1;}
99% {background: url(image_4) 0 0 no-repeat; opacity:0;}
}

使用javascript的另一条路线,有很多选项,但最简单的事情是使用现有的轮播插件。这是我发现的第一个具有自动淡化http://malsup.com/jquery/cycle/int2.html

的人