简单的图片加载类

2005-12-29 21:02:43

用途:图片经常使用onload来改变宽度,但这样会出现图片的闪烁,这个简单的类就是用来解决这个问题的。 在ie6,opera8.5+,ff1.5下测试通过 [code]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <META name="Author" content="Sheneyan" /> <script type="text/javascript"> /************************* *简单的图片加载类 *功能:避免了在img 里直接判断宽高造成屏幕的闪烁 *参数: *url:图片url *id:图片img的id,如果查找不到这个id,将创建一个img,并添加到网页尾部 *maxWidth:最大宽度,可不设置 *maxHeight:最大高度,可不设置 *作者:子乌,sheneyan *************************/ ImageLoader=function(url,id,maxWidth,maxHeight){ this.imgObj=new Image(); this.imgObj.tries=0; this.imgObj.src=url; this.imgObj.uid=id; this.imgObj.maxWidth=maxWidth; this.imgObj.maxHeight=maxHeight; if (!window.ImageLoaders) window.ImageLoaders={}; window.ImageLoaders[id]=this.imgObj; if (!document.all) window.addEventListener('load',function(){document.readyState='complete'},false) window.ImageComplete=function(i){ var obj=window.ImageLoaders[i]; clearInterval(obj.timer); var mw=obj.maxWidth; var mh=obj.maxHeight; var id=obj.uid; if (!document.getElementById(id)){ var img=document.cr&#101;ateElement("img"); img.setAttribute("id",id); img.alt='图像'; document.body.appendChild(img); } var img=document.getElementById(id); if (obj.width>obj.height){ if (mw>0){ if (obj.width>mw) img.width=mw; } } else{ if (mh>0){ if (obj.height>mh) img.height=mh; } } img.src=obj.src; img.style.display=''; window.ImageLoaders[i]=null; } this.imgObj.onload=function(){ window.ImageLoaders[this.uid].timer=setInterval("if (document.readyState=='complete'){window.ImageComplete('"+this.uid+"');}",500); } this.imgObj.onerror=function(){window.status='加载'+this.src+'失败';} } new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303813-Jans.jpg",'i1',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303820-Febs.jpg",'i2',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303832-Mars.jpg",'i3',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303838-Apr.jpg",'i4',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303899-May.jpg",'i5',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/1303899-Jun.jpg",'i6',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/7.jpg",'i61',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/8.jpg",'i62',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/9.jpg",'i63',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/10.jpg",'i64',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/11.jpg",'i65',170,170) new ImageLoader("http://www.blueidea.com/articleimg/2003/12/1461/12.jpg",'i66',170,170) </script> </head> <body> </body> </html> [/code]