jq實現圖片上傳預覽(注意jq版本)
阿新 • • 發佈:2019-01-05
一個jq實現上傳檔案預覽外掛uploadPreview.js
/* *名稱:圖片上傳本地預覽外掛 *引數說明: Img:圖片ID;Width:預覽寬度;Height:預覽高度;ImgType:支援檔案型別;Callback:選擇檔案顯示圖片後回撥方法; *使用方法: <div> <img id="ImgPr" width="120" height="120" /></div> <input type="file" id="up" /> 把需要進行預覽的IMG標籤外 套一個DIV 然後給上傳控制元件ID給予uploadPreview事件 $("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120, ImgType: ["gif", "jpeg", "jpg", "bmp", "png"], Callback: function () { }}); */ 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 } if ($.browser.msie) { try { $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0])) } catch (e) { var src = ""; var obj = $("#" + 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 { $("#" + opts.Img).attr('src', _self.getObjectURL(this.files[0])) } opts.Callback() } }) } });
使用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="lib/js/jq1.7.js"></script> <script type="text/javascript" src="lib/js/uploadPreview.js"></script> </head> <body> <div> <img id="ImgPr" width="120" height="120" /></div> <input type="file" id="up" /> <script type="text/javascript"> $(function(){ $("#up").uploadPreview({ Img: "ImgPr", Width: 120, Height: 120, ImgType: ["gif", "jpeg", "jpg", "bmp", "png"], Callback: function () { }}); }) </script> </body> </html>