H5上傳本地圖片并預(yù)覽功能
最近工作中需要H5上傳顯示圖片的功能,如圖:

直接上代碼:
html部分
<div class="works-wrap"> <div class="figure-box" id="figure_box"></div> <div class="add-btn"> <input type="file" id="imgUploadBtn" /> <a href="javascript:void(0);" rel="external nofollow" ><i></i>添加作品</a></div> </div> </div>
我這邊用css將input[type=file] 設(shè)置成了opticy:0; 這樣可以看起來更像原生的上傳。
var addWork = {
add: function(btn, figure_box) {
var figureBox = document.getElementById(figure_box); //獲取顯示圖片的div元素
var input = document.getElementById(btn); //獲取選擇圖片的input元素
//這邊是判斷本瀏覽器是否支持這個API。
if (typeof FileReader === 'undefined') {
alert("瀏覽器版本過低,請先更新您的瀏覽器~");
input.setAttribute('disabled', 'disabled');
} else {
input.addEventListener('change', readFile, false);
//如果支持就監(jiān)聽改變事件,一旦改變了就運行readFile函數(shù)。
}
function readFile() {
var file = this.files[0]; //獲取file對象
//判斷file的類型是不是圖片類型。
if (!/image\/\w+/.test(file.type)) {
alert("請上傳一張圖片~");
return false;
}
var reader = new FileReader(); //聲明一個FileReader實例
reader.readAsDataURL(file); //調(diào)用readAsDataURL方法來讀取選中的圖像文件
//最后在onload事件中,獲取到成功讀取的文件內(nèi)容,并以插入一個img節(jié)點的方式顯示選中的圖片
reader.onload = function(e) {
// 創(chuàng)建一個新增的圖片和文字input
var figure = $('<div class="figure"><div class="figure-hd">我的頭部</div><div class="figure-bd"><img src="' + this.result + '" /><textarea placeholder="請輸入文字"></textarea></div></div>');
figure.appendTo(figureBox);
}
}
}
}
更多精彩內(nèi)容請參考專題《ajax上傳技術(shù)匯總》,《javascript文件上傳操作匯總》和《jQuery上傳操作匯總》進行學(xué)習(xí)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS 組件系列之Bootstrap Table的凍結(jié)列功能徹底解決高度問題
這篇文章主要介紹了JS 組件系列之Bootstrap Table的凍結(jié)列功能徹底解決高度問題,需要的朋友可以參考下2017-06-06
List Information About the Binary Files Used by an Applicati
List Information About the Binary Files Used by an Application...2007-06-06
websocket4.0+typescript 實現(xiàn)熱更新的方法
這篇文章主要介紹了websocket4.0+typescript 實現(xiàn)熱更新的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
ES6新數(shù)據(jù)結(jié)構(gòu)Set與WeakSet用法分析
這篇文章主要介紹了ES6新數(shù)據(jù)結(jié)構(gòu)Set與WeakSet用法,結(jié)合實例形式簡單分析了Set與WeakSet的功能、使用方法及相關(guān)注意事項,需要的朋友可以參考下2017-03-03

