<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>上传图片</title>
<style>
body,div,img{
margin:0 auto;
padding: 0;
}
html{
width:100%;
height:100%;
}
body{
line-height: 20px;
font-family: "微软雅黑";
width:1000px;
height:100%;
background-color: #000;
}
.upload-img{
position: relative;
text-align: center;
line-height: 300px;
float: left;
margin-top: 100px;
background-color: #fff;
color:#333;
font-size: 30px;
width: 300px;
height: 300px;
margin-left: 15px;
margin-right: 15px;
}
.upload-img .imgs{
position:absolute;
left:0;
top: 0;
width:100%;
height:100%;
}
.upload-img:hover{
color:#f90;
}
.upload-img .btn{
width:100%;
height:100%;
opacity: 0;
filter:alpha(opacity=0);
z-index: 2;
position: absolute;
left: 0;
top: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div class="upload-img">
上传图片
<input type="file" class="btn" onchange="uploadImg(this,1);" />
</div>
<div class="upload-img">
上传图片
<input type="file" class="btn" onchange="uploadImg(this,2);" />
</div>
<div class="upload-img">
上传图片
<input type="file" class="btn" onchange="uploadImg(this,3);" />
</div>
<script>
//上传图片
function uploadImg(that,num){
var parentNode=that.parentNode;
var images=parentNode.getElementsByTagName("img");
if(images.length==0){
createImg(parentNode,num);
}
var img=document.getElementById("img"+num);
var f=that.files;
if(f&&f[0]){
checkedImg(that,f,img);
}else{
//兼容IE
var srcVal=that.value;
if(!srcVal){
alert("你执行了取消操作");
img.setAttribute("src","");
srcVal="";
}else{
var houzui=srcVal.substr(srcVal.lastIndexOf("."))
.replace(".","");
if(houzui=="jpg"||houzui=="jpeg"){
img.setAttribute("src",srcVal);
}else{
alert("请上传后缀名是jpg,jpeg格式的图片");
img.setAttribute("src","");
srcVal="";
}
}
}
}
//创建一张图片
function createImg(parentNode,num){
var imgElement=document.createElement("img");
imgElement.className="imgs";
imgElement.id="img"+num;
parentNode.appendChild(imgElement);
}
//判断图片类型,大小
function checkedImg(that,f,img){
//图片类型
if(f[0].type=="image/jpeg"){
//图片大小不能超过3M
if(f[0].size/1024/1024<3){
var imgSrc=window.URL.createObjectURL(that.files[0]);
img.setAttribute("src",imgSrc);
}else{
alert("上传图片大小不能超过3M");
//清空文件域
f=[];
img.setAttribute("src","");
return false;
}
}else{
alert("请上传后缀名是jpg,jpeg格式的图片");
//清空文件域
f=[];
img.setAttribute("src","");
return false;
}
}
</script>
</body>
</html>