html代碼:
<img id="pic" src="img/pic.png"/>
</span><input id="file" type="file" accept="image/*" capture="camera"/>
注意:IOS和Android有兼容性問題,IOS只能拍照,不能從相冊選擇
解決:
1 $(function () { 2 //解決上傳圖片時capture="camera"在安卓與IOS的兼容性問題(在IOS只能拍照,不能選相冊)
3 var ua = navigator.userAgent.toLowerCase();//獲取瀏覽器的userAgent,並轉化為小寫——注:userAgent是用戶可以修改的
4 var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);//判斷是否是蘋果手機,是則是true
5 if (isIos) { 6 $("input:file").removeAttr("capture"); 7 }; 8 })
js代碼:
//選擇圖片后自動填充
//獲取對象input file 的圖片地址,放進img
$("#file").change(function () {//input的id
var objUrl = getObjectURL(this.files[0]);//調用函數調取圖片地址
obUrl = objUrl;
console.log("objUrl = " + objUrl);
if (objUrl) {
$("#pic").attr("src", objUrl).show();//選擇img的ID,給src賦值
}
});
//獲取input file的文件地址
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) {//basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) {//mozilla(firefox)兼容火狐
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {//webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}