jquery实现图片上传

如果页面中有使用LayUi框架需要上传多张图片时需要删除form 中 class=“layui-form” ,不然上传不了多张图片

<style>.imageDiv {display:inline-block;width:100px;height:100px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;border:1px dashed darkgray;background:#f8f8f8;position:relative;overflow:hidden;margin:10px}.cover {position:absolute;z-index:1;top:0;left:0;width:100px;height:100px;background-color:rgba(0,0,0,.3);display:none;line-height:125px;text-align:center;cursor:pointer;}.cover .delbtn {color:red;font-size:10px;}.imageDiv:hover .cover {display:block;}.addImages {display:inline-block;width:100px;height:100px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;border:1px dashed darkgray;background:#f8f8f8;position:relative;overflow:hidden;margin:10px;}.text-detail {margin-top:10px;text-align:center;}.text-detail span {font-size:40px;}.file {position:absolute;top:0;left:0;width:100px;height:100px;opacity:0;}
</style><div style="width: 70%;margin: 0 auto"><div id="Pic_pass"><p style="font-weight: bold;">请上传图片</p><p><span style="color: red">注:每张图片大小不可超过4M,一次最多可以上传4,多张上传时必须按住ctrl选中</span></p><div class="picDiv"><div class="addImages"><input type="file" class="file" name="file[]" id="fileInput" multiple="multiple" accept="image/png, image/jpeg, image/gif, image/jpg"><div class="text-detail"><span>+</span><p>点击上传</p></div></div></div></div><div class="msg" style="display: none;"></div>
</div><script>//图片上传预览功能var userAgent = navigator.userAgent; //用于判断浏览器类型$(".file").change(function() {//获取选择图片的对象var docObj = $(this)[0];var picDiv = $(this).parents(".picDiv");//得到所有的图片文件var fileList = docObj.files;//循环遍历for (var i = 0; i < fileList.length; i++) {//动态添加html元素var picHtml = "<div class='imageDiv' > <img id='img" + fileList[i].name + "' /> <div class='cover'><i class='delbtn'>删除</i></div></div>";// console.log(picHtml);picDiv.prepend(picHtml);//获取图片imgi的对象var imgObjPreview = document.getElementById("img" + fileList[i].name);if (fileList && fileList[i]) {//图片属性imgObjPreview.style.display = 'block';imgObjPreview.style.width = '100px';imgObjPreview.style.height = '100px';//imgObjPreview.src = docObj.files[0].getAsDataURL();//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式if (userAgent.indexOf('MSIE') == -1) {//IE以外浏览器imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]); //获取上传图片文件的物理路径;// console.log(imgObjPreview.src);// var msgHtml = '<input type="file" id="fileInput" multiple/>';} else {//IE浏览器if (docObj.value.indexOf(",") != -1) {var srcArr = docObj.value.split(",");imgObjPreview.src = srcArr[i];} else {imgObjPreview.src = docObj.value;}}}}/*删除功能*/$(".delbtn").click(function() {var _this = $(this);_this.parents(".imageDiv").remove();});});
</script>

在这里插入图片描述

删除图片:

在这里插入图片描述

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注