jquery实现图片预加载- Y! V( L2 p" K3 N! I
js代码
6 e3 C& w0 Z, i( t+ E$(function(){ loadimg(); function loadimg(url,callback){ var img = new image(); img.onload = function(){ img.onload = null; callback(img); } img.src=url; img.width =202; img.height = 202; img.attr(defaulturl,../images/img.png); if(){} } function addimg(img){ $(img).appendto($(.imgload li)) } })
$ w9 H8 T9 H. w; E9 R A* l+ fhtml:
1 {0 y( v' F2 z- p3 P: s<!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>图片预加载</title> <link rel=stylesheet type=text/css href=css/index.css> <script type=text/javascript src=js/jquery-1.8.3.min.js></script> <script type=text/javascript src=js/index.js></script> </head> <body> <div class=imgload> <ul> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> <li class=fl></li> </ul> </div> </body> </html> 7 C3 g7 o3 g h X% a/ H8 Q
其他实例
0 [! _+ g5 e1 f& J$ _3 k1 Y sfunction loadimg(arr,funloading,funonload,funonerror){ var numloaded=0, numerror=0, isobject=object.prototype.tostring.call(arr)===[object object] ? true : false; var arr=isobject ? arr.get() : arr; for(a in arr){ var src=isobject ? $(arr[a]).attr(data-src) : arr[a]; preload(src,arr[a]); } function preload(src,obj){ var img=new image(); img.onload=function(){ numloaded++; funloading && funloading(numloaded,arr.length,src,obj); funonload && numloaded==arr.length && funonload(numerror); }; img.onerror=function(){ numloaded++; numerror++; funonerror && funonerror(numloaded,arr.length,src,obj); } img.src=src; } } ' a) ^/ c4 V$ _+ c
参数说明:# n$ {" ]- w# { D, m/ Q3 s* P
arr:可以是存放图片路径的一个数组,也可以是选取到的img的jquery对象;8 X+ g: o2 \7 V2 V
funloading:每一个单独的图片加载完成后执行的操作;& A+ j; i8 t3 v& h/ n+ J$ m
funonload:全部图片都加载完成后的操作;+ c; h) o: }# W' q, g3 b% X
funonerror:单个图片加载出错时的操作。
& K/ V2 S- P( N5 j9 h+ U3 {懒加载,9 }- _3 m) g% q6 q: B0 p0 t$ x5 a
var imgonload=function(errors){ /*errors:加载出错的图片数量;*/ console.log(loaded,+errors+ images loaded error!); } var funloading=function(n,total,src,obj){ /* n:已加载完成的数量; total:总共需加载的图片数量; src:当前加载完成的图片路径; obj:当loadimg函数中传入的arr为存放图片路径的数组时,obj=src,是图片路径, 当arr为jquery对象时,obj是当前加载完成的img dom对象。 */ console.log(n+of+total+ pic loaded.,src); var newimg = document.createelement(img); newimg.src=src; $(body).append(newimg).fadein(); } var funloading_obj=function(n,total,src,obj){ console.log(n+of+total+ pic loaded.,src); $(obj).attr(src,src); $(obj).fadein(200); } var funonerror=function(n,total,src,obj){ console.log(the +n+st img loaded error!); }
7 h6 r L. b; I i; r" G调试用例
+ l8 h. ?0 m1 j, C8 x1 `; Z4 |console.log(loading...); loadimg($(img),funloading_obj,imgonload,funonerror); /*loadimg([, , , , ],funloading,imgonload,funonerror);*/
, q! r. C" o/ ?# q' m2 b7 @6 @# ~5 L
更多网页制作信息请查看: 网页制作 |
|