(function($) { $.imageFileVisible = function(options) { // 默认选项 var defaults = { //包裹图片的元素 wrapSelector: null, //<input type=file />元素 fileSelector: null , width : ‘100%‘, height: ‘auto‘, errorMessage: "不是图片" }; var opts = $.extend(defaults, options); $(opts.fileSelector).on("change",function(){ var file = this.files[0]; var imageType = /image.*/; if (file.type.match(imageType)) { var reader = new FileReader(); reader.onload = function(){ var img = new Image(); img.src = reader.result; $(img).width( opts.width); $(img).height( opts.height); $( opts.wrapSelector ).append(img); }; reader.readAsDataURL(file); }else{ alert(opts.errorMessage); } }); }; })(jQuery);
这是对 FileReader的进一步封装 html代码为:
<input type="file" id="file"> <div id="image-wrap"></div>
但是要事先引入jQuery和这个jq插件
传参方式如下:
<html> <meta charset="utf-8"> <title>input标签选择file直接读取本地图片并显示</title> <body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script src="image-file-visible.js"> </script> <script> $(document).ready(function(){ //图片显示插件 $.imageFileVisible({wrapSelector: "#image-wrap", fileSelector: "#file", width: 100, height: 50 }); }); </script> <input type="file" id="file"> <div id="image-wrap"></div> </body> </html>
时间: 2024-12-16 09:54:07