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

Simple jquery .css background change image with delay

本文关键字:图像 延迟 改变 背景 jquery css 简单      更新时间:2023-09-26

我想在我的welcome_boxdiv中使用jquery及时更改背景。

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

我不需要点击或任何东西,只是自动淡入大约4个图像,与延迟5秒为每个图像淡入

我找不到一个简单的代码,有人能帮我吗?

您的标记无效。试试这个

<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,有很多选择,但最简单的方法是使用现有的carousel插件。这是我发现的第一个有自动淡出功能的http://malsup.com/jquery/cycle/int2.html

试一下

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…等等