javascript – 拖放图像输入文件并预览上传前

前端之家收集整理的这篇文章主要介绍了javascript – 拖放图像输入文件并预览上传前前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个div附加拖放功能,当有人点击它,他们可以选择他们的形象.

我已经编码了一些东西,它的可以
– 点击div并选择您的图像
上传前预览您的图像

你可以检查我的小提琴

CSS

  1. .uploader {width:300px;height:350px;background:#f3f3f3;border:2px dashed #e8e8e8;}

JavaScript的

  1. var imageLoader = document.getElementById('filePhoto');
  2. imageLoader.addEventListener('change',handleImage,false);
  3.  
  4. function handleImage(e) {
  5. var reader = new FileReader();
  6. reader.onload = function (event) {
  7.  
  8. $('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' );
  9. }
  10. reader.readAsDataURL(e.target.files[0]);
  11. }

HTML

  1. <div class="uploader" onclick="$('#filePhoto').click()">click here or drag here your images for preview and set userprofile_picture data</div>
  2. <input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" />

你可以检查
http://jsfiddle.net/ELcf6/

解决方法

你可以用很少的CSS技巧来做到这一点.
输入元素接受下降.
我改变了你的代码如下:

CSS

  1. .uploader {
  2. position:relative;
  3. overflow:hidden;
  4. width:300px;
  5. height:350px;
  6. background:#f3f3f3;
  7. border:2px dashed #e8e8e8;
  8. }
  9.  
  10. #filePhoto{
  11. position:absolute;
  12. width:300px;
  13. height:400px;
  14. top:-50px;
  15. left:0;
  16. z-index:2;
  17. opacity:0;
  18. cursor:pointer;
  19. }
  20.  
  21. .uploader img{
  22. position:absolute;
  23. width:302px;
  24. height:352px;
  25. top:-1px;
  26. left:-1px;
  27. z-index:1;
  28. border:none;
  29. }

JavaScript的

  1. var imageLoader = document.getElementById('filePhoto');
  2. imageLoader.addEventListener('change',false);
  3.  
  4. function handleImage(e) {
  5. var reader = new FileReader();
  6. reader.onload = function (event) {
  7. $('.uploader img').attr('src',event.target.result);
  8. }
  9. reader.readAsDataURL(e.target.files[0]);
  10. }

HTML

  1. <div class="uploader" onclick="$('#filePhoto').click()">
  2. click here or drag here your images for preview and set userprofile_picture data
  3. <img src=""/>
  4. <input type="file" name="userprofile_picture" id="filePhoto" />
  5. </div>

我希望它有帮助.您可以查看http://jsfiddle.net/ELcf6/4/和其他版本http://jsfiddle.net/ELcf6/8/

猜你在找的JavaScript相关文章