简易图片点击上传预览示例。chrome,火狐等浏览器下可支持拖拽预览 1. [代码] [HTML]代码 !DOCTYPEhtmlhead meta http-equiv="Content-Type" content="text/html; charset=utf-8" script type="text/javascript" //--从 file 域
1. [代码][HTML]代码
<!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> //--从 file 域获取 本地图片 url function getFileUrl(sourceId) { var url; if (navigator.userAgent.indexOf("MSIE")>=1) { // IE url = document.getElementById(sourceId).value; } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } return url; } var ss=null var ImgType=["gif", "jpeg", "jpg", "bmp", "png","ico"]; //--将本地图片 显示到浏览器上 function preImg(obj, targetId) { ss=obj; if (!RegExp("\.(" + ImgType.join("|") + ")$", "i").test(obj.value.toLowerCase())) { alert("选择文件错误,图片类型必须是" + ImgType.join(",")); this.value = ""; return false } var sourceId=obj.id var url = getFileUrl(sourceId); var imgPre = document.getElementById(targetId); imgPre.src = url; } </script> </head> <body> <form action=""> <label style="position: relative;width:100px;height:100px;display: block;line-height:100px; " align="center"> <input type="file" accept="image/*" name="imgOne" id="imgOne" onchange="if(this.value){preImg(this, 'imgPre');}" style="height: 100%;width: 100%;position: absolute;z-index: 9;left: 0;right: 0;opacity: 0;"/> <img id="imgPre" src="" style="display: block;position: absolute;width:100%;height:100%;border: 1px solid #999;"/> 上传图片 </label> </form> </body> </html>