http://www.imooc.com/video/14434 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片无序预加载</title> <style type="text/css"> body{padding: 0;margin: 0;height: 100%} .box{text-align: center;} .btn{display: inline-block;height: 30px;line-height: 30px;border: 1px solid #ccc;background: #fff;padding: 0 10px;margin-right: 50px;color: #333;text-decoration: none} .btn:hover{background: #eee;} .box img{max-width: 1200px;max-height: 500px} .loading{position: fixed;width: 100%;height: 100%;top: 0;left: 0;background: rgba(0,0,0,.8);text-align: center;font-size: 30px;} .progress{margin-top: 300px;color: #fff;} </style> </head> <body> <div class="box"> <img src="http://img2.xcabc.com/201706/02/20170602053032832519.jpg" alt=""> <p> <a href="javascript:;" class="btn" data-control="pre">上一页</a> <a href="javascript:;" class="btn" data-control="next">下一页</a> </p> </div> </body> <div class="loading"> <p class="progress">0%</p> </div> <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> (function($){ function preLoad(imgs,options){ this.imgs = (typeof imgs === 'string') ? [imgs] : imgs; this.opts = $.extend({},preLoad.DEFAULTS,options); this._unordered(); } preLoad.DEFAULTS = { each:null, all:null }; preLoad.prototype._unordered = function(){ var imgs = this.imgs, opts = this.opts, count = 0, len = imgs.length; $.each(imgs, function(i, src) { if(typeof src != 'string') return; var imgObj = new Image(); $(imgObj).on('load error',function(){ opts.each && opts.each(count); if(count >= len-1 ){ opts.all && opts.all(); } count ++; }); imgObj.src = src; }); }; $.extend({ preLoad:function(imgs,opts){ new preLoad(imgs, opts); } }); })(jQuery); </script> <script type="text/javascript"> var imgs = [ 'http://img2.xcabc.com/201706/08/20170608045825651696.jpg', 'http://img2.xcabc.com/201706/06/20170606054203570721.jpg', 'http://img2.xcabc.com/201706/06/20170606054205719522.jpg', 'http://img2.xcabc.com/201705/19/20170519025222518532.jpg', 'http://img2.xcabc.com/201705/19/20170519025232980526.jpg' ]; var index = 0, len = imgs.length; // count = 0, $progress = $('.progress'); $.preLoad(imgs, { each:function(count) { $progress.html(Math.round((count+1) / len * 100) + '%'); }, all:function(){ $('.loading').hide(); document.title = '1/' + len; } }); // $.each(imgs, function(i, src) { // var imgObj = new Image(); // $(imgObj).on('load error',function(){ // $progress.html(Math.round((count+1) / len * 100) + '%'); // if(count >= len-1 ){ // $('.loading').hide(); // document.title = '1/' + len; // } // count ++; // }); // imgObj.src = src; // }); $('.btn').on('click',function(){ if($(this).attr('data-control') === 'pre'){ index = Math.max(0, --index); }else{ index = Math.min(len - 1, ++index); } document.title = (index + 1) + '/' + len; $('.box img').attr('src',imgs[index]); }); </script> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » js学习之 图片无序预加载 喜欢 (0)or分享 (0)