您好,欢迎来到吉趣旅游网。
搜索
您的当前位置:首页jquery中图片无序预加载的实现以及使用方法

jquery中图片无序预加载的实现以及使用方法

来源:吉趣旅游网

本篇文章给大家带来的内容是关于jquery中图片无序预加载的实现以及使用方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

/图片无序预加载
(function($){


function Preload(imgs,fns){

this.imgs=(typeof imgs==="string")?[imgs]:imgs;

this.fns=$.extend({},Preload.fns,fns);//把fns 覆盖到Preload上 然后添加到{}返回

if(this.fns.loadMethod=="unorderload"){//是无序 还是有序

this._unorderload();
}
else{

this._orderload();

}
}

Preload.fns={
loadMethod:null,//有序还是无序的方式
eachLoadImg:null, //每张图片加载完所执行的函数
allLoadImg:null //所有图片加载完所要执行的函数
}
Preload.prototype._orderload=function(){
var imgs=this.imgs,
len=imgs.length,
fns=this.fns,
num=0;
function load(){
var imgObj=new Image();
$(imgObj).on("load error",function(){
fns.each && fns.each(); //存在 才会执行
if(num<len){
load(); //没有加载完就继续加载 函数执行是有顺序的
}
else{
fns.allLoadImg && fns.allLoadImg();//加载完全部
}
});
imgObj.src=imgs[num];
num++;
}
load();
}
Preload.prototype._unorderload=function(){
var imgs=this.imgs,
len=imgs.length,
fns=this.fns,
num=0;
$.each(imgs,function(i,src){

if(typeof src!="string") return;

var imgObj=new Image();
$(imgObj).on("load error",function(){

fns.eachLoadImg && fns.eachLoadImg(num,len);

if( num==len-1){

fns.allLoadImg && fns.allLoadImg();
}
num++;
});
imgObj.src=src;

});

}
$.extend({ //给jQuery上增加新函数

preload:function(imgs,fns){

new Preload(imgs,fns);

}

});

})(jQuery);

使用方法

<!doctype html>
<html>
 <head>
 <meta charset="UTF-8">
 <meta name="Generator" content="EditPlus?">
 <meta name="Author" content="">
 <meta name="Keywords" content="">
 <meta name="Description" content="">
 <title>有序预加载</title>
 <style>
 *{margin: 0; padding: 0;}
 
 img{
 width:100%;
 vertical-align:top;
 
 }
 .imgBox{
 width:500px;
 margin:100px auto;
 
 
 }
 #prevImg, #nextImg{
 
 width:60px;
 font-size:15px;
 height:30px;
 line-height:30px;
 text-align:center;
 background: #686868;
 position:absolute;
 color:#000;
 text-decoration:none;
 margin-top:-50px;
 }

 #prevImg{
 
 left:40%;
 
 }

 #nextImg{
 
 left:55%;
 
 }

 </style>
 <script src="js/jquery-3.2.1.js"></script>
 <script src="js/unorderload.js"></script>
 <script>
 
 $(function(){
 
 
 
 var imgs=["img/0.jpg","img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg","img/5.jpg","img/6.jpg","img/7.jpg"];
 var len=imgs.length;
 var index=0;
 $.preload(imgs,{});

 $("#control-img-btn").on("click","a",function(){
 

 
 if($(this).hasClass("prevImg")){
 
 index=Math.max(0,--index); //上一张
 }

 else{
 
 index=Math.min(len-1,++index);//下一张
 
 }

 $("#imgBox img").attr("src",imgs[index]);
 
 
 });

 });
 


 </script>
 </head>
 <body>
 <div id="imgBox">
 <img />
 </div>
 <p id="control-img-btn">
 <a href="javascript:;" id="prevImg">上一页</a>
 <a href="javascript:;" id="nextImg">下一页</a>
 </p>
 </body>
</html>

Copyright © 2019- jqkq.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务