标签:replace 实现 nbsp 判断 pad auto oat node set
1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <title>上传图片</title> 6 <style> 7 body,div,img{ 8 margin:0 auto; 9 padding: 0; 10 } 11 html{ 12 width:100%; 13 height:100%; 14 } 15 body{ 16 line-height: 20px; 17 font-family: "微软雅黑"; 18 width:1000px; 19 height:100%; 20 background-color: #000; 21 22 } 23 .upload-img{ 24 position: relative; 25 text-align: center; 26 line-height: 300px; 27 float: left; 28 margin-top: 100px; 29 background-color: #fff; 30 color:#333; 31 font-size: 30px; 32 width: 300px; 33 height: 300px; 34 margin-left: 15px; 35 margin-right: 15px; 36 } 37 .upload-img .imgs{ 38 position:absolute; 39 left:0; 40 top: 0; 41 width:100%; 42 height:100%; 43 } 44 .upload-img:hover{ 45 color:#f90; 46 } 47 .upload-img .btn{ 48 width:100%; 49 height:100%; 50 opacity: 0; 51 filter:alpha(opacity=0); 52 z-index: 2; 53 position: absolute; 54 left: 0; 55 top: 0; 56 cursor: pointer; 57 } 58 </style> 59 </head> 60 <body> 61 <div class="upload-img"> 62 上传图片 63 <input type="file" class="btn" onchange="uploadImg(this,1);" /> 64 </div> 65 <div class="upload-img"> 66 上传图片 67 <input type="file" class="btn" onchange="uploadImg(this,2);" /> 68 </div> 69 <div class="upload-img"> 70 上传图片 71 <input type="file" class="btn" onchange="uploadImg(this,3);" /> 72 </div> 73 </body> 74 </html>
1 //上传图片 2 function uploadImg(that,num){ 3 var parentNode=that.parentNode; 4 var images=parentNode.getElementsByTagName("img"); 5 if(images.length==0){ 6 createImg(parentNode,num); 7 } 8 var img=document.getElementById("img"+num); 9 var f=that.files; 10 if(f&&f[0]){ 11 checkedImg(that,f,img); 12 }else{ 13 //兼容IE 14 var srcVal=that.value; 15 if(!srcVal){ 16 alert("你执行了取消操作"); 17 img.setAttribute("src",""); 18 srcVal=""; 19 }else{ 20 var houzui=srcVal.substr(srcVal.lastIndexOf(".")) 21 .replace(".",""); 22 if(houzui=="jpg"||houzui=="jpeg"){ 23 img.setAttribute("src",srcVal); 24 }else{ 25 alert("请上传后缀名是jpg,jpeg格式的图片"); 26 img.setAttribute("src",""); 27 srcVal=""; 28 } 29 } 30 31 } 32 } 33 //创建一张图片 34 function createImg(parentNode,num){ 35 var imgElement=document.createElement("img"); 36 imgElement.className="imgs"; 37 imgElement.id="img"+num; 38 parentNode.appendChild(imgElement); 39 } 40 //判断图片类型,大小 41 function checkedImg(that,f,img){ 42 //图片类型 43 if(f[0].type=="image/jpeg"){ 44 //图片大小不能超过3M 45 if(f[0].size/1024/1024<3){ 46 var imgSrc=window.URL.createObjectURL(that.files[0]); 47 img.setAttribute("src",imgSrc); 48 }else{ 49 alert("上传图片大小不能超过3M"); 50 //清空文件域 51 f=[]; 52 img.setAttribute("src",""); 53 return false; 54 } 55 }else{ 56 alert("请上传后缀名是jpg,jpeg格式的图片"); 57 //清空文件域 58 f=[]; 59 img.setAttribute("src",""); 60 return false; 61 } 62 }
标签:replace 实现 nbsp 判断 pad auto oat node set
原文地址:http://www.cnblogs.com/wuchanglong/p/6032034.html