首页 > 解决方案 > FadeIn 新的背景图像 Jquery

问题描述

我有一个定义了背景图像的 div:

#section0{
        background-image: url("images/top_back2.jpg");
    }

我有一个 setTimeout 函数在 3 秒后将背景图像更改为其他内容

    $("#section0").css("background-image", "url(images/top_back.jpg)");
        }, 3000);

这工作正常,但无论我尝试什么,我似乎都无法让这个图像淡入。

任何想法都将不胜感激,它只是像这样出现在屏幕上,而且非常刺耳。我无法将 CSS3 淡入添加到整个元素中,因为前 3 秒内没有显示内部内容,我需要它出现。

谢谢!

标签: javascriptjqueryfadeinfadefadeout

解决方案


您还必须定义它如何淡化它,您可以使用它opacity来实现此效果,然后是transition定义动画属性的参数,例如持续时间和缓动。

CSS:

#section0{
     opacity: 0;
     transition: opacity 2s; /* Define the duration of the opacity animation */
     background-image: url("images/top_back2.jpg");
}

JavaScript(在您的 setTimeout 内):

$("#section0").css({
     "opacity" : 1,
     "background-image": "url(images/top_back.jpg)"
});

Here is a demo on JSFiddle with the code https://jsfiddle.net/wtbmdaxc/

Enjoy :)


Update:

To avoid the text to being covered, there are two ways to do it, either you separate your background image into another DIV and apply the opacity to that new DIV or you create a pseudo-element. Both of which have already been answered on SO before.

Let's try the first method, how it will work in your case

HTML:

<div id="section0">
  Example test. Lorem ipsum dolor sit amet.
  <div id="bg-opacity"></div>
</div>

CSS:

#section0{
}

#section0 #bg-opacity{
     position: absolute; /* Force this layer to appear at the top left of the div */
     top: 0;
     left: 0;
     z-index: -1; /* Makes the image appear in the back and not covering the texts */
     opacity: 0;
     transition: opacity 2s; /* Define the duration of the opacity animation */
     height: 500px;
     width: 500px;
     background-image: url("https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif");
}

JavaScript:

setTimeout(function(){ 
  $("#bg-opacity").css({
       "opacity" : 1,
       "background-image": "url(https://media.giphy.com/media/tIeCLkB8geYtW/giphy.gif)"
  });
}, 300);

And a new demo on JSFiddle: https://jsfiddle.net/zr7Lf0m5/


推荐阅读