jquery图像加载

时间:2011-12-18 07:41:30

标签: ajax image jquery load

我有这样的代码:

<div id="gallery">
   <img src="image1.jpg">
   <img src="image2.jpg">
   <img src="image3.jpg">
</div>

我想显示标准(对于ajax请求)动画gif,同时图片正在加载,当它加载时显示完整图像。

只有一个要求要保留当前标记并在单独的脚本块中对onload执行所有必需的操作

1 个答案:

答案 0 :(得分:0)

我认为你可以使用ajaxStart和ajaxComplete事件(jQuery)

<div id="indicator"><img src="/path/to/your/image.gif"/></div>

$("#indicator").bind("ajaxStart", function(){
    $(this).show();
});

$("#indicator").bind("ajaxComplete", function(){
    $(this).hide();
});

当你使用$ .ajax或$ .post时,它会在ajax请求开始和停止时自动显示和隐藏加载器。

或者如果使用XmlHttpRequest,则可以基于readyState of XmlHttpRequest对象来设置指标图像。

例如:

xmlHttp.onreadystatechange=function(){ 
    if (xmlHttp.readyState==4){ 
        document.getElementById("yourDiv").innerHTML=xmlHttp.responseText;
    }else if(xmlHttp.readyState==3){
        document.getElementById("yourDiv").innerHTML="<img src='loader.gif' />Loading...";
   }
}

将readyState作为:

  • 0未初始化:初始值。
  • 1打开:已成功调用open()方法。
  • 2已发送:UA已成功完成请求,但尚未收到任何数据。
  • 3接收:在收到消息正文(如果有)之前。已收到所有HTTP标头。

源:http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/