【问题标题】:FadeIn new background image JqueryFadeIn 新的背景图像 Jquery
【发布时间】:2020-02-20 07:45:48
【问题描述】:

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

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

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

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

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

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

谢谢!

【问题讨论】:

  • 你想在哪里fadeIn这里?
  • 我试过在第一行末尾的分号之前。 $("#section0").css("background-image", "url(images/top_back.jpg)") .fadeIn(1000); }, 3000);

标签: javascript jquery fadein fade fadeout


【解决方案1】:

您还必须定义它如何淡化它,您可以使用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/

【讨论】:

  • 感谢您的帮助。这确实有效,但 #section0 div 中的内容也被隐藏了。我需要从一开始就显示出来。有什么方法可以让内容仍然显示?
  • @Andrei 用应该解决这个问题的方法更新了我的答案:)
  • 看起来很有希望,我会试一试!非常感谢
  • 当然,如果我的回答解决了您的问题,请将其标记为有帮助。干杯!
  • 我对此有一些额外的问题,它出现的页面使用 fullPage.js。文档说“您必须将选择器视为动态元素并使用委托。(通过使用诸如来自 jQuery 的东西)。”知道如何使用上面的代码实现这一点吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 2011-01-08
  • 1970-01-01
相关资源
最近更新 更多