圖片預加載事件,我們如何點擊選擇圖片後直接顯示在頁面上呢?
呢麼我們來看demo詳情。如下所示:
頁面demo如下所示:
<img id="photos" src="" width="100" height="100" />
<input id="files" type="file" onchange="chan(this)" name="files" />
js代碼:
<script src="~/Scripts/jquery-1.10.2.js"></script>
//瀏覽圖片
function chan(i) {
var objUrl = getObjectURL(i.files[0]);
if (objUrl) {
$("#photos").attr("src", objUrl); //這裏的id是要顯示圖片位置的Id
}
};
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null;
// 下面函數執行的效果是一樣的,只是需要針對不同的瀏覽器執行不同的 js 函數而已
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;
}
</script>