jQuery实现多张图片上传预览(不经过后端处理)

效果图:

图(1)

图(2)

代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery图片上传预览(不经过后端处理)</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<div>
 <img class="ImgPr"/>
 <input type="file" class="up" />
</div>
<div>
 <img class="ImgPr"/>
 <input type="file" class="up" />
</div>
<script>
jQuery.fn.extend({
   uploadPreview: function(opts) {
    var _self = this,
      _this = $(this);
    opts = jQuery.extend({
     Img: "ImgPr",
     Width: 100,
     Height: 100,
     ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
     Callback: function() {}
    }, opts || {});
    _self.getObjectURL = function(file) {
     var url = null;
     if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
     } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
     } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
     }
     return url
    };
    _this.change(function() {
     if (this.value) {
      if (!RegExp("\.(" + opts.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
       alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种");
       this.value = "";
       return false
      }
      //高版本Jquey使用 if ($.support.leadingWhitespace)
      if ($.support.leadingWhitespace) { //低版本jquery中使用$.browser.msie

       console.log(_self.getObjectURL(this.files[0]));
       try {
        _this.parent('div').find("." + opts.Img).attr('src', _self.getObjectURL(this.files[0]));
       } catch (e) {
        var src = "";
        var obj = _this.parent('div').find("." + opts.Img);
        var div = obj.parent("div")[0];
        _self.select();
        if (top != self) {
         window.parent.document.body.focus()
        } else {
         _self.blur()
        }
        src = document.selection.createRange().text;
        document.selection.empty();
        obj.hide();
        obj.parent("div").css({
         'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)',
         'width': opts.Width + 'px',
         'height': opts.Height + 'px'
        });
        div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src
       }
      } else {
       _this.parent('div').find("." + opts.Img).attr('src', _self.getObjectURL(this.files[0]))
      }
      opts.Callback()
     }
    })
   }
  });
  $(".up").click(function(){
   $(this).uploadPreview({
    Img: "ImgPr"
   });
  })

</script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。