JS中图片缓冲loading技术的实例代码
var Imgvalue;
var Count =13; //图片数量
var Imgs = new Array(Count);
var ImgLoaded =0;
//预加载图片
function preLoadImgs()
{
alert('图片加载中请稍等......');
for(var i=0;i<Imgs.length;i++){
Imgs[i]=new Image();
downloadImage(i);
}
}
//加载单个图片
function downloadImage(i)
{
var imageIndex = i+1; //图片以1开始
Imgs[i].src = "images/"+imageIndex+".jpg";
Imgs[i].onLoad=validateImages(i);
}
//验证是否成功加载完成,如不成功则重新加载
function validateImages(i){
if (!Imgs[i].complete)
{
window.setTimeout('downloadImage('+i+')',200);
}
else if (typeof Imgs[i].naturalWidth != "undefined" && Imgs[i].naturalWidth == 0)
{
window.setTimeout('downloadImage('+i+')',200);
}
else
{
ImgLoaded++
if(ImgLoaded == Count)
{
document.getElementById('BtnStart').disabled=false;
document.getElementById('BtnStop').disabled=false;
alert('图片加载完毕!');
}
}
}
//开始
function RandStart()
{
Init = setInterval('SetRand()',50);
}
//随机显示
function SetRand()
{
imageIndex = Math.floor(Math.random()*Count);
document.getElementById("ImgView").src = Imgs[imageIndex].src;
}
//结束
function RandStop()
{
window.clearInterval(Init);
}