HTML代码如下:
<!-- date: 2018-04-27 14:41:35 author: 王召波 descride: HTML5上传图片预览功能 --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML5上传图片预览功能</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <style type="text/css"> #feedback{ min-height: 200px; text-align: center; border: 1px solid silver; border-radius: 3px; } #feedback img{ margin:3px 10px; border: 1px solid silver; border-radius:3px; padding: 6px; width: 35%; height: 85%; } #feedback p{ font-family: "微软雅黑"; line-height: 120px; color: #ccc; } .file { position: relative; display: inline-block; border: 1px solid #1ab294; border-radius: 4px; padding: 8px 16px; overflow: hidden; color: #fff; text-decoration: none; text-indent: 0; line-height: 20px; color: #1ab294; } .file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; } .box{ margin-top: 10px; text-align: center; } .box a{ margin-left: 10px; } </style> </head> <body> <!-- 响应返回数据容器 --> <div id="feedback"> </div> <div class="box"> <a href="javascript:;" class="file">选择图片 <input type="file" id="inputfile" name="" class="photo"> </a> <a href="javascript:;" class="file close">重新选择 <input type="buttom" class="photo"> </a> </div> <script type="text/javascript"> $(function () { $("#inputfile").change(function (e) { var imgURL = ''; var file = e.target.files[0] || e.dataTransfer.files[0]; if (file) { try{ try{ imgURL = file.getAsDataURL(); }catch(e){ imgURL = window.URL.createObjectURL(file); } }catch(e){ var reader = new FileReader(); reader.onload = function () { imgURL = this.result; } reader.readAsDataURL(file); } $("#feedback").append('<img src="'+imgURL+'">');; } }); }) </script> </body> </html>
效果图: