日期:2014-05-16  浏览次数:20493 次

JavaScript 实现图片待上传预览

<html>
<head></head>
<script type="text/javascript"> 
function preview5(){ 
	document.getElementById("delImgButton").style.display = "none";
    var x = document.getElementById("file5"); 
	if(!x || !x.value) return; 
	var patn = /\.jpg$|\.jpeg$|\.gif$|\.bmp$/i;
	if(patn.test(x.value)){ 
		var imgType = checkImgType(x.value);
		var num = document.getElementById("num").value;
		if(num==3){
			alert("最多只能上传 3 张图片");return;
		}
		num++;
		document.getElementById("num").value = num;
		var img  = "img"+num;
		var y = document.getElementById(img); 
		if(y){ 
			y.src = "file://localhost/" + x.value; 
		}else{ 
			var imgObject=document.createElement("img"); 
			imgObject.setAttribute("src","file://localhost/"+x.value); 
			imgObject.setAttribute("width","180"); 
			imgObject.setAttribute("height","140"); 
			imgObject.setAttribute("id",img);
			imgObject.setAttribute("value",x.value);
			var delSpan = document.getElementById("delImgButton");
			//imgObject.setAttribute("onmouseover",function(){delSpan.style.display ="block"})
			imgObject.setAttribute("onclick",function(){delSpan.style.display ="block";document.getElementById("delImgId").value=this.id;})
			document.getElementById("form5").appendChild(imgObject);
			
			
		} 
	}else{ 
		alert("您选择的似乎不是图像文件。"); 
	}
}

function checkImgType(img){
	var jpgPatn = /\.jpg$|\.JPG$/i;
	var jpegPatn = /\.jpeg$|\.JPEG$/i;
	var gifPatn = /\.gif$|\.GIF$/i;
	var bmpPatn = /\.bmp$|\.BMP$/i;
	
	if(jpgPatn.test(img)){
		return "jpg";
	}else if(jpegPatn.test(img)){
		return "jpeg";
	}else if(gifPatn.test(img)){
		return "gif";
	}else if(bmpPatn.test(img)){
		return "bmp";
	}
}
function initImg(){
	document.getElementById("num").value = 0 ;
}

function delImg(){
	var imgId = document.getElementById("delImgId").value;
	var remImgObjcet = document.getElementById(imgId);
	document.getElementById("delImgButton").style.display = "none";
	document.getElementById("form5").removeChild(remImgObjcet);
	var returnId = imgId.substring(imgId.length,imgId.length-1);
	document.getElementById("num").value = parseInt(returnId)-1;
}

function imgV(){
	var i = document.getElementById("img1").value;
	alert(i);
	
}

</script> 

<title>img preview</title>
<body onload="initImg()">
<form name="form5" id="form5" method="post" action="#">
<input type="hidden" name="num" id="num" value="0"/>
<input type="hidden" name="delImgId" id="delImgId"/>
<input type="file" name="file5" id="file5"  onchange="preview5()"/> <br>
</form>
<div>
<span id="delImgButton" style="width:150px;height:20px;display:none;"><a href="#" onClick="delImg()">删除图片</a></span>
</div>
<input type="button" value="imgValue" onclick="imgV()">
</body>
</html>[/code="html"]