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>
相关推荐
songshijiazuaa 2020-09-24
bbccaaa 2020-07-28
newcome 2020-04-29
Web全栈笔记 2020-05-03
vs00ASPNET 2020-04-29
jinxiutong 2020-04-23
cuiwenjie 2020-04-18
chouliqingke 2020-02-13
breakpoints 2020-01-29
poplpsure 2019-12-28
nxcjh 2020-01-03
tiankele0 2020-01-05
H女王范儿 2019-12-29
且听真言 2019-12-21
前端架构师 2019-12-19
webgm 2019-10-25