javascript - FadeIn 新背景图像 Jquery

标签 javascript jquery fadein fade fadeout

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

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

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

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

这工作正常,但无论我如何尝试,我似乎都无法使该图像淡入

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

谢谢!

最佳答案

您还必须定义它如何淡入淡出,您可以使用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)"
});

这是 JSFiddle 上的演示及其代码 https://jsfiddle.net/wtbmdaxc/

享受吧:)

<小时/>

更新:

为了避免文字被覆盖,有两种方法可以做到,要么 separate your background image into another DIV并将不透明度应用于新的 DIV 或您 create a pseudo-element 。这两个问题之前都已经在 SO 上得到了回答。

让我们尝试第一种方法,看看它在您的情况下如何工作

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

JSFiddle 上有一个新的演示:https://jsfiddle.net/zr7Lf0m5/

关于javascript - FadeIn 新背景图像 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533400/

相关文章:

javascript - 在 material-ui 中打开扩展面板时删除额外空间

javascript - 如何使用 CSS/JavaScript 在链接上取消悬停?

jquery - 使 Nivo Slider 在加载时淡入

jquery - 简单的 JQuery .fadeIn 事件在我的浏览器上无法正常工作

javascript - WebCrypto API 在哪里存储 key ?

javascript - 使用 javascript 循环 101 102 …

javascript - 当 jquery animate :left function? 离开内部 div 模式时如何将 div 隐藏在 div 中

jQuery - "preloading"(setinterval)的效果?

javascript - jQuery 从页面上的字符串中获取总和或数字

jquery - Chrome 中 jQuery fadeIn() 和 fadeOut() 的问题