图片上传预览

来源:互联网 发布:移动内网外网切换软件 编辑:程序博客网 时间:2024/05/29 08:09
  1. 头像上传预览
<div id="previewLicence" class="iden-rec">     <i class="iconfont pic">&#xe651;</i></div>   <input autocomplete="off" class="em-btn" type="file"  name="Licence" data-img-preview="previewLicence" />

div为图片容器,给它绑定一个id关联input上传文件的data-*自定义属性,用属性控件绑定事件。
设置图片上传图片的支持格式:
给input type=file 标签设置属性accept accept=”image/jpeg,image/x-png,image/png”,如果不限制图像的格式,可以写为:accept=”image/*”。

自定义绑定事件部分代码:

$(document).ready(function() {    window.previewLocalImageFile = function(source, previewContainer) {        console.info(previewContainer.attr("id"));        console.info(source.files[0]);        if (source.files) {            if(source.files[0]) {                $(source).data("has-file", true);                previewContainer.html("");                var img = document.createElement("img");                previewContainer.append(img);                img.onload = function() {                    img.style.width = "100%";                    img.style.height = "100%";                }                var reader = new FileReader();                reader.onload = function(evt) {                    img.src = evt.target.result;                }                reader.readAsDataURL(source.files[0]);            }        } else { //兼容IE            source.select();            source.blur();            var src = document.selection.createRange().text;            if(src) {                $(source).data("has-file", true);                previewContainer.html("");                var img = document.createElement("img");                previewContainer.append(img);                var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';                img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;                previewContainer.html("<div style='width:100%;height:100%;" + sFilter + src + "\"'></div>");            }        }    };    function _init() {        $("input[type='file']").each(function() {            var containerId = $(this).data("img-preview");            if (containerId) {                var $this = this;                console.info($this.name);                var previewContainer = $("#" + containerId);                previewContainer.click(function() {                    $this.click();                });                $($this).change(function() {                    previewLocalImageFile(this, previewContainer);                });            }        });    }    _init();});
0 0
原创粉丝点击