知识点:
var myImg = new Image();
本质上就是虚拟创建一个img标签,存储已经加载好的图片。
myImg.src则是img的路径;
css
*{
margin:0;
padding:0;
}
body,html{
width: 100%;
height: 100%;
}
a{
text-decoration: none;
}
.btn{
display: inline-block;
border:1px solid #ccc;
background: #fff;
font-size: 14px;
padding: 5px 10px;
margin-right: 35px;
color: #666;
}
.btn:hover{
background: #eee;
}
.box{
text-align: center;
}
.img{
width: 800px;
margin-bottom: 20px;
}
.loading{
width: 100%;
height: 100%;
position:fixed;
left: 0;
top: 0;
background: #eee;
}
.progress{
font-size: 30px;
position: absolute;
top: 50%;
margin-top: -30px;
left: 50%;
}
html
<div class="box">
<img src="http://s16.sinaimg.cn/orignal/3ea244b9g79e6249ed12f&690" alt="" class="img">
<p>
<a href="javascript:;" class="btn" data-control="prev">上一页</a>
<a href="javascript:;" class="btn" data-control="next">下一页</a>
</p>
</div>
<div class="loading">
<p class="progress">0%</p>
</div>
js
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<script>
$(function(){
var imgs=[
'http://s16.sinaimg.cn/orignal/3ea244b9g79e6249ed12f&690',
'http://www.deskcar.com/desktop/fengjing/201342152514/11.jpg',
'http://attimg.dospy.com/img/day_120403/20120403_ff7d00e3c8890ac99d0ft829Pq8AcoeE.jpg',
'http://attimg.dospy.com/img/day_120721/20120721_b827a9d749e4d5da6bf6686626zZVAXV.jpg',
'http://img.club.pchome.net/kdsarticle/2014/05/14/c11841cb92ea1ea96cd2bdc232e38515.jpg',
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524649284378&di=9a5d70caecd6fdaff87c68e0ab66b37b&imgtype=0&src=http%3A%2F%2Fwww.blue1000.com%2Fupload%2F2010-07%2F100708090875221.jpg',
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524649284378&di=c21297d4c0d2b75e64d41fe1b73ae284&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F35a85edf8db1cb1353fd8b78de54564e93584bc0.jpg',
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524649284363&di=61e67e80de4efbf37aa819279e483b53&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F4afbfbedab64034fc321c2edaac379310b551d68.jpg',
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524649284355&di=504c4ec88902ad330c96a2bfa92bdcf1&imgtype=0&src=http%3A%2F%2Fa3.topitme.com%2Fb%2F22%2F79%2F11493575500237922bo.jpg'
]
var len = imgs.length,
index = 0,
count = 0;//目前加载了的张数
//设置预加载图片路径
$.each(imgs,function(i,val){
var imgObj = new Image();
$(imgObj).on("load error",function(){
$('.progress').html(Math.round((count +1) / len *100 )+"%");
if(count >= len-1){
$(".loading").hide();
}
count++;
})
imgObj.src =val;
})
// 无预加载功能
$(".btn").click(function(){
// 控制index的值不能无限++或--
if(index<=0){
index = 0
}else if(index>=len-1){
index = len-1;
}
// 点击按钮时的判断
if($(this).data("control") === "prev"){//上一张
Math.max(0,--index);
// console.log('prev:'+index);
}else{//下一张
Math.min(len-1,++index);
// console.log('next'+index);
}
$(".img").attr('src',imgs[index]);
})
})
</script>