JavaScript图片预加载代码,完后载入显示loading
第一种是不错的方法噢:
一、<html>
<head>
<style type="text/css">
div{border:#aaaaaa 3px solid;width:200px;padding:2px;margin:2px 9px;font-size:12px;line-height:22px;color:#999999;}
.ipt1{width:160px;font-size:12px;color:#1F6478;border:#999999 1px solid;margin-left:9px;}
.ipt2{border:#999999 1px solid;margin-left:6px;color:#666666}
p{margin:0px;padding:0px;background-image:url(http://www.codefans.net/jscss/demoimg/loading.gif);background-position:center;background-repeat:no-repeat;width:200px;height:200px;text-align:center;font-size:12px;color:#999999;line-height:26px;}
</style>
<script language="javascript" type="text/javascript">
function preloadimg(url,obj,ipt){
var img=new Image();
obj.innerHTML="<p>图片加载中...</p>";
img.onload=function(){
alert(ipt.name);
obj.innerHTML="";
obj.style.width=String(img.width)+"px";
ipt.style.width=String(img.width-40)+"px";
obj.appendChild(img);
};
img.onerror=function(){
obj.innerHTML="图片加载失败!"
};
img.src=url; //img.src一定要写在img.onload之后,否则在IE中会出现问题
}
function show(){
var div=document.getElementsByTagName("div")[0];
var input=document.getElementsByTagName("input");
preloadimg("http://www.xd26.com/photo/up_files/2009-03-27/1238121079Qa5x.jpg",div,input[0]);
input[0].onclick=function(){this.value=""};
input[1].onclick=function(){preloadimg(input[0].value,div,input[0]);}
}
window.onload=show;
</script>
<title>JavaScript图片预加载代码,显示loading</title>
</head>
<body>
<div></div>
<br />
<input type="text" value="将图片地址粘贴在这里" class="ipt1"/>
<input type="button" value="开始加载" class="ipt2"/>
</body>
</html>
二、
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
<script>
var imgID = new Image();
imgID.src = "http://www.xd26.com/photo/up_files/2009-03-27/1238121079Qa5x.jpg";
imgID.onload = function(){
document.getElementById("jia").innerHTML = "<img src="+imgID.src+" >";
}
</script>
<div id="jia">Loading...</div>
</body>
</html>