Display image when preview button is click before upload in jQuery
本问题已经有最佳答案,请猛点这里访问。
我有一个像这样的HTML表单:
1 2 3 4 5 6 7 8 9 | <form id="myForm" name="myform" action="register/index.php" method="post" enctype="multipart/form-data"> <input class="myfile" id="banner" name="banner" type="file" accept="image/png, image/gif, image/jpeg"> Preview <input type="submit" value="submit" name="submit"> </form> |
我想要做的是当用户点击预览按钮时,他所选择的文件将显示在
1 2 3 4 | function getPreview(){ // what should write here to make this working } |
有人请帮忙,如何使用jQuery或JavaScript?
试试这个,可能会有所帮助,否则你可以根据你的要求定制更多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function readURL(input) { $('.preview').show(); $('#blah').hide(); $('.preview').after('<img id="blah" src="#" alt="your image" style="display:none;"/>'); if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(150) .height(200); }; reader.readAsDataURL(input.files[0]); } } function getPreview(){ $('.preview').hide(); $('#blah').show(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE html> <html> <head> <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"> <meta charset=utf-8 /> JS Bin <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> <![endif]--> <style> article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } </style> </head> <body> <input type='file' onchange="readURL(this);" /> Preview<br/> </body> </html> |