如何在div #content加载时显示div #loading

use*_*287 5 html jquery loading

我想要实施一个解决方案,其中:

  1. 而div #content中的内容正在加载,
  2. 隐藏div #content,
  3. show div #loading,
  4. 然后当div #content加载时,
  5. hide div #loading,
  6. 淡出div #content

我试过了:

HTML:

<div id="content">
<!--this stuff takes a long time to load-->
<img src="http://lorempixel.com/1920/1920/">
</div>
<div id="loading">
<!-- this is the loading gif -->
<img src="http://lorempixel.com/400/200/">
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

// when user browses to page
$('#content').hide();
$('#loading').show();

// then when div #content has loaded, hide div #loading and fade in div #content
$('#content').bind('load', function() {
$('#loading').hide();
$('#content').fadeIn('slow');
});
Run Code Online (Sandbox Code Playgroud)

这是我正在研究的jsfiddle:

http://jsfiddle.net/rwone/Y9CQ4/

谢谢.

Ola*_*che 9

根据.load(),事件应该触发,何时触发

当load和所有子元素已完全加载时,load事件将发送到元素.此事件可以发送到与URL关联的任何元素:图像,脚本,框架,iframe和窗口对象.

因此,您无法将load事件处理程序绑定到div标记.如果希望在加载图像后触发事件处理程序,则必须将其绑定到图像

HTML:

<div id="content">
<!--this stuff takes a long time to load-->
<img id="large" src="http://lorempixel.com/1920/1920/">
</div>
<div id="loading">
<!-- this is the loading gif -->
<img src="http://lorempixel.com/400/200/">
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

// when user browses to page
$('#content').hide();
$('#loading').show();

// then when the #content div has loaded
$('#large').bind('load', function() {
$('#loading').hide();
$('#content').fadeIn('slow');
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

或者您可以将事件绑定到window对象,该对象在何时触发

页面已满载,包括图形.

JS:

$(window).bind('load', function() {
$('#loading').hide();
$('#content').fadeIn('slow');
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

第三种方法是在加载事件触发时测试是否加载了所有图像

function allImagesLoaded() {
    var imgs = $(this).closest('div').find('img');
    var loaded = 0;
    imgs.each(function() { if ($(this.complete)) ++loaded; });
    if (imgs.length == loaded) {
        $('#loading').hide();
        $('#content').fadeIn('slow');
    }
}

// when user browses to page
$('#content').hide();
$('#loading').show();

// then when the #content div has loaded
$('#content img').bind('load', allImagesLoaded);
Run Code Online (Sandbox Code Playgroud)

的jsfiddle