【问题标题】:Update background after all items have loaded加载所有项目后更新背景
【发布时间】:2015-01-13 16:09:42
【问题描述】:

我有这个问题,我的网络应用程序加载了一个大图像作为背景。它应用在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. 加载图像时,将背景更改为图像

【问题讨论】:

  • 尝试查看js控制台...你看到任何错误吗?
  • 尝试使用 FireBug 扩展并密切注意“网络”选项卡。可能是您的图像位置或文件名不正确。 getfirebug.com
  • firebug 控制台(网络)中没有错误 404

标签: javascript jquery html css


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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 - link

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多