图片预加载实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body,html{
width: 100%;
height: 100%;
}
.img{
width: 100%;
height: 80%;
}
img{
width: 100%;
height: 100%;
}
button{
width: 100px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: azure;
color: black;
display: inline-block;
cursor: pointer;
border: 0;
}
.prev{
margin: 10px 0 0 40%;
}
button:hover{
color: red;
background-color: darkcyan;
}
.hint{
position: fixed;
width: 100%;
height: 20px;
background-color: floralwhite;
color: black;
text-align: center;
}
</style>
</head>
<body>
<div class="hint"></div>
<div class="img">
<img src="https://cdn.pixabay.com/photo/2016/12/14/04/08/ray-1905603__340.png" alt="">
</div>
<button class="prev">上一页</button>
<button class="next">下一页</button>
<!-- 可以引用百度cdn的jq -->
<script src="../jquery-3.2.1.min.js"></script>
<script>
(function() {
var $but = $('button');
var $img = $('img');
var $hint= $('.hint');
var conunt = 0;
var imgs = [
'https://cdn.pixabay.com/photo/2016/12/14/04/08/ray-1905603__340.png',
'https://cdn.pixabay.com/photo/2017/08/30/17/26/to-reach-2697951__340.jpg',
'https://cdn.pixabay.com/photo/2017/12/30/18/29/rome-3050680__340.jpg',
'https://cdn.pixabay.com/photo/2016/11/06/05/38/landscape-1802340__340.jpg',
'https://cdn.pixabay.com/photo/2016/07/19/04/40/moon-1527501__340.jpg',
'https://cdn.pixabay.com/photo/2017/12/26/02/59/the-fishermen-3039592__340.jpg',
]
var len = imgs.length;
var index = 0;
$.each(imgs,function (i,Img_addr) {
/*
$.each 遍历循环出 imgs 数组内容
下面创建一个imgObj 用来缓存图片
*/
var imgObj = new Image();
/*
new Image() 创建一个对象,类似于 createElementNode('img')
会触发两个事件
load,error
循环加载 出 imgs 对象里面的数据
*/
$(imgObj).on('load',function(){
// 当加载的时候,我们可以通过这个来得到我们的加载情况
$hint.html( Math.round((conunt + 1) / len * 100)+ '%');
conunt++;
});
// 给与我们新创建的img
imgObj.src = Img_addr;
});
// 点击切换下一张图片
/*
min,max 从给予的两个值中返回一个最大或者最小值
*/
$but.on('click',function(){
var option = $(this).html();
if( option === '下一页'){
index = Math.min( len, ++index ); // 每次都选择最小的
$img.attr('src',imgs[index]);
}
else{
index = Math.max(0, --index);
$img.attr('src', imgs[index]);
}
})
// 输出,callback
function x(y){
console.log(y)
}
})()
</script>
</body>
</html>