如何在input標(biāo)簽選擇文件并直接顯示本地圖片
在網(wǎng)頁中,有時我們需要讓用戶能夠選擇本地的圖片文件,并且能夠直接在頁面上顯示出來。使用filereader可以實現(xiàn)這個功能,下面是具體的步驟。 第一步:創(chuàng)建HTML結(jié)構(gòu) 首先,在頁面中引入jQue
在網(wǎng)頁中,有時我們需要讓用戶能夠選擇本地的圖片文件,并且能夠直接在頁面上顯示出來。使用filereader可以實現(xiàn)這個功能,下面是具體的步驟。
第一步:創(chuàng)建HTML結(jié)構(gòu)
首先,在頁面中引入jQuery庫,并添加一個文件選擇的input元素以及一個用于顯示結(jié)果的div。
lt;script src""gt;lt;/scriptgt;
lt;input type"file" id"file"gt;
lt;div id"image-wrap"gt;lt;/divgt;
第二步:創(chuàng)建jQuery插件image-file-visible.js
為了方便以后的使用,我們可以創(chuàng)建一個jQuery插件來處理圖片顯示的邏輯。
(function($) {
$.imageFileVisible function(options) {
// 默認(rèn)選項
var defaults {
// 包裹圖片的元素
wrapSelector: null,
// input typefile元素
fileSelector: null,
width: '100%',
height: 'auto',
errorMessage: "不是圖片"
};
// Extend our default options with those provided.
var opts $.extend(defaults, options);
$().on("change", function(){
var file [0];
var imageType /image.*/;
if ((imageType)) {
var reader new FileReader();
function(){
var img new Image();
;
$(img).width(opts.width);
$(img).height(opts.height);
$( opts.wrapSelector ).append(img);
};
(file);
} else {
alert();
}
});
};
})(jQuery);
第三步:完整的HTML代碼
下面是完整的HTML代碼:
lt;!DOCTYPE htmlgt;
lt;htmlgt;
lt;headgt;
lt;meta charset"utf-8"gt;
lt;titlegt;input標(biāo)簽選擇file直接讀取本地圖片并顯示lt;/titlegt;
lt;script src""gt;lt;/scriptgt;
lt;script src"image-file-visible.js"gt;lt;/scriptgt;
lt;scriptgt;
$(document).ready(function(){
// 圖片顯示插件
$.imageFileVisible({
wrapSelector: "image-wrap",
fileSelector: "file",
width: 100,
height: 50
});
});
lt;/scriptgt;
lt;/headgt;
lt;bodygt;
lt;input type"file" id"file"gt;
lt;div id"image-wrap"gt;lt;/divgt;
lt;/bodygt;
lt;/htmlgt;
通過以上三個步驟,我們就可以在網(wǎng)頁中使用input標(biāo)簽選擇本地文件,并且直接顯示出圖片了。