加载所有项目后更新背景

Update background after all items have loaded

本文关键字:更新 背景 项目 加载      更新时间:2023-09-26

我遇到了这个问题,我的网络应用程序加载了一个大图像作为背景。它应用于body标签顶部的<style>标签中。它可以工作,但是当打开页面时,图像加载时会显示白色背景。

我希望能够在图像加载时将background-color设置为特定的蓝色,所以我这样做了:

在正文结束标记之前:

     <script type="text/javascript">
        $(document).foundation();
        $(document).ready(function() {
            document.body.style.backgroundImage="url('img/form_bg.jpg')";
            //$('body').css('background-image', 'url(img/form_bg.jpg) no-repeat center center fixed');
        });
    </script>

但是,此代码不起作用,并且不会加载后台。这个坚持:

body {
    /*background:transparent;*/
    background-color:#2f3255;
}

我怎样才能实现这一点:

  1. 在图像加载时制作背景色:#2f3255
  2. 加载图像时,将背景更改为图像

您可以在 DOM 中添加一个额外的div ( #intro ),在加载背景图像时覆盖整个屏幕:

.CSS:

#intro {
   width: 100%;
   position: fixed;
   top: 0;
   bottom: 0;
   z-index: 100;
   background-color:#2f3255;
}

然后,当页面加载时,只需隐藏该div:

$(window).load(function() {
    // You could add a time out here if you like (setTimeout(function() { $('#intro').fadeOut();   }, 500))
    $('#intro').fadeOut();    
});

您可以预加载图像并在下载时应用它,如下所示:

var backgroundImage = new Image();
backgroundImage.onload = function() {
    document.body.style.backgroundImage = "url('" + this.src + "')";
}
backgroundImage.src = 'img/form_bg.jpg';

第一次下载会缓存图像,因此浏览器第二次尝试请求它并将其应用为背景时,它会从那里获取它。此外,如果图像已从以前的请求中缓存,则"onload"会立即触发。你不必把它包装在"body.onload"函数或"$(document).ready()"中,如果你想让它在页面仍然加载时可见。

编辑:这是一个jsfiddle - 链接