【问题标题】:CSS Fade in background image when loadedCSS 加载时淡入背景图像
【发布时间】:2017-11-08 15:59:09
【问题描述】:

我的页面有默认背景颜色和背景图片。

如果完全加载,我希望在图像完全加载之前显示默认背景颜色。只有图片加载完毕后,才能淡入。

到目前为止,我已经能够很好地淡入背景图像,但即使没有完全加载,图像也会淡入。

我想实现类似于WeTransfer的东西

这是我的代码:

HTML

<div id="container-background">

<div id="child-background">

  <p>Text</p>

</div> <!--container-background-->

</div> <!-- child-background-->

CSS

#container-background
{
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
}

#child-background
{
  background: #17181a;
  transition: background 0.7s linear;
  -webkit-transition: background 0.7s linear;
  height: 100%;
  width: 100%;
  background-image: url(https://c1.staticflickr.com/4/3804/11129952164_63075cdbe9_b.jpg);"
}

JS

$('#child-background').css('background', 'rgba(255, 255, 255, 0)');

Fiddle

请帮助我仅在加载时淡入背景图像,尚未加载时显示默认背景颜色。

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

从 css 中删除背景图片并试试这个:

$('<img/>').attr('src', 'https://c1.staticflickr.com/4/3804/11129952164_63075cdbe9_b.jpg').load(function() {
     $('#child-background').css('background-image','url(https://c1.staticflickr.com/4/3804/11129952164_63075cdbe9_b.jpg)');
    });
#container-background
{
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
}

#child-background
{
  background: #17181a;
  transition: background 0.7s linear;
  -webkit-transition: background 0.7s linear;
  height: 100%;
  width: 100%;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container-background">

<div id="child-background">

  <p>Text</p>

</div> <!--container-background-->

</div> <!-- child-background-->

【讨论】:

  • 您可以添加完整的代码,以便我们看到结果:)
  • 谢谢雷切尔。我想让图像在加载图像时出现,而不是窗口。我页面上的所有内容都很轻,除了背景图片很重,加载时间比其他内容长。
【解决方案2】:

试试这个。

$(function(){
    var bgimage = new Image();      
    bgimage.src="https://www.switchbacktravel.com/sites/default/files/images/articles/Hiking%20photo.jpg";       
    $("#child-background").hide();     
    $(bgimage).load(function(){
        $("#child-background").css("background-image","url("+$(this).attr("src")+")").fadeIn(2000); 
     }); 
});
body{
  margin:0;
}
#container-background
{  
  height: 100vh;
  width: 100%;
  background:#000;
}
#child-background
{
  background-color: #17181a;
  background-repeat:no-repeat;
  background-size:cover;
  transition: background 0.7s linear;
  -webkit-transition: background 0.7s linear;
  height: 100vh;
  width: 100%; 
  
}
p{
  margin:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container-background">
  <div id="child-background">  
  <p>Text</p> 
</div> <!--container-background-->
</div> <!-- child-background-->

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2017-08-16
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多