標籤:relative oat ast rcv indexof 代碼 position ret str
<!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>
原生js實現即時預覽代碼