有时候_1
2017-05-15 20:50
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>预加载之有序加载</title>
<style>
.box {
text-align: center;
}
.btn {
display: inline-block;
height: 30px;
line-height: 30px;
border: 1px solid #ccc;
background-color: #fff;
padding: 0 10px;
margin-right: 50px;
color: #333;
}
.btn:hover {
background-color: #eee;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<div class="box">
<img src="http://45.34.137.202:8080/comicdata/12307/1/0.jpg" alt="pic" id="img" width="1200">
<p>
<a href="javascript:;" class="btn" data-control='prev'>上一页</a>
<a href="javascript:;" class="btn" data-control='next'>下一页</a>
</p>
</div>
<script src='../jquery/jquery-3.2.1.min.js'></script>
<script>
var imgs = [
'http://45.34.137.202:8080/comicdata/12307/1/0.jpg',
'http://45.34.137.202:8080/comicdata/12307/1/1.jpg',
'http://45.34.137.202:8080/comicdata/12307/1/2.jpg',
'http://45.34.137.202:8080/comicdata/12307/1/3.jpg',
'http://45.34.137.202:8080/comicdata/12307/1/4.jpg'
];
var len = imgs.length,
count = 0,
index = 0;
load();
//有序预加载
function load() {
var imgObj = new Image();
$(imgObj).on('load error', function() { //load后触发一个方法
if(count >= len) {
//所有图片加载完毕
} else {
if(count <= index+2)
load();
}
count++;
});
imgObj.src = imgs[count];
//将当前图片的路径赋值各给图片对象的scr来开始预加载
// console.log(count);
};
$('.btn').on('click', function(){
if('prev'=== $(this).data('control')) {
if(index == 0) {
alert('已经是第一张了')
}
index = Math.max(0, --index);
}else {
if(index == len-1) {
alert('已经是最后一张了')
}
index = Math.min(len-1, ++index);
}
document.title = (index + 1) + '/' + len;
$('#img').attr('src', imgs[index]);
//点击按钮显示到index对应的图片
count = count-2;
load();
});
</script>
</body>
</html>
....<a>标签忘记加class了吧 加上试试
图片预加载
40980 学习 · 81 问题
相似问题