圖片上傳預覽(可兼容IE8)


function uploadPreview (setting) { //圖片上傳預覽
/*this(當前對象)*/
var _self = this;

/*判斷為null或者空值*/
_self.IsNull = function (value) {
if (typeof (value) == "function") {
return false;
}
if (value == undefined || value == null || value == "" || value.length == 0) {
return true;
}
return false;
};

/*默認配置 */
_self.DefautlSetting = {
UpBtn: "",
DivShow: "",
ImgShow: "",
Width: 100,
Height: 100,
ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
ErrMsg: "選擇文件錯誤,圖片類型必須是(gif,jpeg,jpg,bmp,png)中的一種",
callback: function () {}
};

/*讀取配置 */
_self.Setting = {
UpBtn: _self.IsNull(setting.UpBtn) ? _self.DefautlSetting.UpBtn : setting.UpBtn,
DivShow: _self.IsNull(setting.DivShow) ? _self.DefautlSetting.DivShow : setting.DivShow,
ImgShow: _self.IsNull(setting.ImgShow) ? _self.DefautlSetting.ImgShow : setting.ImgShow,
Width: _self.IsNull(setting.Width) ? _self.DefautlSetting.Width : setting.Width,
Height: _self.IsNull(setting.Height) ? _self.DefautlSetting.Height : setting.Height,
ImgType: _self.IsNull(setting.ImgType) ? _self.DefautlSetting.ImgType : setting.ImgType,
ErrMsg: _self.IsNull(setting.ErrMsg) ? _self.DefautlSetting.ErrMsg : setting.ErrMsg,
callback: _self.IsNull(setting.callback) ? _self.DefautlSetting.callback : setting.callback
};

/*獲取文本控件URL */
_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;
};

/*綁定事件 */
_self.Bind = function () {
document.getElementById(_self.Setting.UpBtn).onchange = function () {
Upimg(this);
};

function Upimg(Upbtn) {
var div = document.getElementById(_self.Setting.DivShow);
var img = document.getElementById(_self.Setting.ImgShow);

if (Upbtn.value) {
if (!RegExp("\.(" + _self.Setting.ImgType.join("|") + ")$", "i").test(Upbtn.value.toLowerCase())) {
alert(_self.Setting.ErrMsg);
return false;
}
if (navigator.userAgent.indexOf("MSIE") > -1) { //IE
try {
img.src = _self.getObjectURL(Upbtn.files[0]);
} catch (e) {
Upbtn.select();
top.parent.document.body.focus();
var src = document.selection.createRange().text;
document.selection.empty();
img.style.display = "none";
div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
}
} else { //谷歌火狐
img.style.display = 'block';
img.src = _self.getObjectURL(Upbtn.files[0]);
}
_self.Setting.callback();
}
}
};
_self.Bind();
}

 

 

/********注:********/

input type=“file” ,不可隱藏,也不可模擬點擊觸發事件,在IE下會因為安全性造成提交失敗;

解決:label for指向對應input的id,label也不可被模擬點擊觸發事件;


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: