图片预加载--无序

2018-01-25

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*重置样式*/
*{
margin: 0;
padding: 0;
}
a{
color: #444;
text-decoration: none;
}
ul{
list-style:none;
}
html{
font-size: 14px;
}

.imgwrap{
width: 60%;
margin: 1rem auto;
position: relative;
}

.imglist,.pagelist{
text-align: center;
}
.imgwrap,.imglist,.imglist li{
height: 500px;
}

.imglist img{
width: 100%;
height: 100%;
}

.pagelist a.btn{
display: inline-block;
padding: 0.5em;
margin-left: 2rem;
border:1px solid #ccc;
}
.pagelist a.btn:hover{
background: #ccc;
color: #fff;
}

.loading{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
font-size: 3rem;
background: #ccc;
}
.progress{
text-align: center;
line-height: 500px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="wrap">
<div class="imgwrap">
<ul class="imglist">
<li><a href=""><img src="img/1.jpg" alt="" id="img"></a></li>
</ul>
<div class="loading">
<div class="progress">0%</div>
</div>
</div>
<div class="pagelist">
<a href="javascript:;" class="btn" data-control="prev">上一页</a>
<a href="javascript:;" class="btn" data-control="next">下一页</a>
</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var imgs=[
'img/1.jpg',
'img/2.jpg',
'img/3.jpg',
'img/4.jpg',
'img/5.jpg',
'img/6.jpg',
'img/7.jpg',
'img/8.jpg',
'img/9.jpg',
'img/10.jpg',
'img/11.jpg',
'img/12.jpg',
'img/13.jpg',
'img/14.jpg',
'img/15.jpg',
'img/16.jpg',
'img/17.jpg',
'img/18.jpg',
'img/19.jpg',
'img/20.jpg'
];
var index = 0,
len = imgs.length,
count = 0,
$progress=$('.progress');

$.each(imgs,function(i,src){
var imgObj = new Image();

$(imgObj).on('load', 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('prev' === $(this).data('control')){//上一张
index = Math.max(0,--index);
}else{//下一张
index = Math.min(len - 1,++index);
}
document.title = (index + 1) + '/' + len;
$('#img').attr('src',imgs[index]);
});