且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用jQuery显示加载指示器

更新时间:2023-12-05 16:49:34

您可以将侦听器绑定到每个的load事件图片。使用计数器或其他机制来跟踪每次调用侦听器时加载的图像数。然后在加载最后一个图像后隐藏加载指示器。例如:

You can bind a listener to the load event of each image. Use a counter or some other mechanism to keep track of how many images are loaded each time the listener is invoked. Then hide the loading indicator after the last image is loaded. For example:

HTML

<span id="loading" style="display:none">Loading...</span>
<div class="images">
    <img class="large-image" src="http://astritademi.files.wordpress.com/2011/04/happy_panda.jpg" width="893" height="548" />
    <img class="large-image" src="http://www.pandafix.com/pandafix/images/r3387761054.jpg" width="275" height="199" />
    <img class="large-image" src="http://farm1.static.flickr.com/149/357563212_f8b89ac6d8.jpg" width="500" height="375" />
</div>

jQuery

$(function() {
    var images = $('.large-image')
      , total = images.length
      , count = 0;

    $('#loading').show();
    images.load(function() {
        count = count + 1;
        if (count >= total) {
            $('#loading').hide();
        }
    });
});

你可以在jsFiddle上看到这个例子: http://jsfiddle.net/hallettj/ZefaM/

You can see this example in action on jsFiddle: http://jsfiddle.net/hallettj/ZefaM/