JS原生实现本地图片上传预览

来源:互联网 发布:淘宝 优衣库 便宜 编辑:程序博客网 时间:2024/05/17 03:02
执行方式如下:
$("input").change(function() {var config = {imgWrapWidth: 300, //pximgWrapHeight: 200, //pximgMaxWidth: "100%",imgMaxHeight: "100%",};ImgShow(this, "result", config);});
函数:
function ImgShow(arg, showWrapId, config) {//input的状态change的时候,执行此函数,需要把input用this的方式传递进来,三个参数必须有//arg=this   showWrapId=图片显示框的ID     config=显示框的大小和图片显示的大小//图片在显示框中绝对居中
//config = {//imgWrapWidth: 300, //px//imgWrapHeight: 200, //px//imgMaxWidth: "100%",//imgMaxHeight: "100%",//};var file = arg.files[0];if(!/image\/\w+/.test(file.type)) {alert("请上传图片!");} else {var reader = new FileReader();//将文件以Data URL形式读入页面  reader.readAsDataURL(file);reader.onload = function(e) {var showWrap = document.getElementById(showWrapId);showWrap.style.width = config.imgWrapWidth + "px";showWrap.style.height = config.imgWrapHeight + "px";showWrap.style.textAlign = "center";//显示文件  showWrap.innerHTML = "<span style='vertical-align: middle;display: inline-block;height: 100%;'></span>" +"<img style='vertical-align: middle;display: inline-block;max-width:" + config.imgMaxWidth + ";max-height:" + config.imgMaxHeight + ";'" +" src='" + this.result + "' alt='' />";}}

                                             
0 0
原创粉丝点击