js实现图片上传预览功能

点点圈 提交于 2020-02-27 00:52:20

html:

<div class="aui-col-xs-3" id="img">

 <div class="aui-grid-label">添加图片</div>
 <div id="upImg">
 <input type="file" name="file" id="chooseImage" />
 </div>
 <div id="imgPreview">
 <img src="#" id="cropedBigImg" />
 </div>
</div>

css:



#img {
 float: left;
 margin-left: 20px;
 width: 150px;
 height: 60px;
 }
#upImg {
 position: absolute;
 top: 0px;
 left: 0px;
}
#upImg input {
 width: 70px;
 height: 60px;
 opacity: 0;
}
#imgPreview {
 width: 80px;
 height: 60px;
 position: absolute;
 left: 70px;
 top: 0px;
}
#cropedBigImg{
 width: 100%;
 height: 100%;
 display: none;
}
	$(function() {
   	$("#chooseImage").change(function() {
   		//当chooseImage的值改变时,执行此函数
   		var filePath = $(this).val(), //获取到input的value,里面是文件的路径
   			fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
   			src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式

   		// 检查是否是图片
   		if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
   			alert('上传错误,文件格式必须为:png/jpg/jpeg');
   			return;
   		} else {
   			$(".bbDImg span").text("");
   			$('#cropedBigImg').css('display', 'block');
   			$('#cropedBigImg').attr('src', src);
   			
   		}
   	});


   })
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!