效果:
代码
<!DOCTYPE html> <html> <head> <title>图片上传</title> <meta charset="utf-8"> <style type="text/css"> .show-place{ width: 600px; height: 50px; position: relative; } .btn-upload{ float: left; display: block; width: 100px; height: 100px; border: 1px solid #ddd; background: #ebebeb; line-height: 100px; font-size: 14px; text-align: center; color: #808080; } .show-place img{ float: left; width: 100px; height: 100px; margin-right: 10px; } </style> </head> <body> <form> <div class="show-place"> <label for="btn-upload" class="btn-upload">点击上传</label> <input type="file" name="imgs" onchange="previewImg(this);" style="display: none;" id="btn-upload"> </div> </form> </body> </html> <!--<script type="text/javascript" src="jquery-2.2.1.min.js"></script>--> <script type="text/javascript"> function previewImg(fileElement) { var showPlace =document.getElementsByClassName("show-place")[0]; //FileReader if(window.FileReader){//验证当前的浏览器是否支持图片预览 var reader=new FileReader(); var file=fileElement.files[0]; var regexImage=/^image\//;//匹配是否拥有image,确保上传的文件是图片 if(regexImage.test(file.type)){ //设置读取结束的回调函数 reader.onload=function(){ ShowImg(showPlace,this); }; //开始读取上传的文件内容 reader.readAsDataURL(file); }else{ return false; } }else{ console.log("亲,浏览器该升级了,不支持图片预览~"); return false; } } //显示添加的图片 function ShowImg(showPlace,self){ var btnElement=document.getElementsByClassName("btn-upload")[0]; var imgElement=document.createElement("img"); imgElement.src=self.result; showPlace.insertBefore(imgElement,btnElement); } </script>