jquery多图片上传预览
程序员文章站
2022-06-14 14:54:32
...
我知道你们喜欢硬的,来吧,直接上代码,废话不多说
css
#renGongImg .imageDiv {
display:inline-block;
width:65px;
height:65px;
-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
}
#renGongImg .cover {
position:absolute;
z-index:1;
top:0;
left:0;
width:65px;
height:65px;
background-color:rgba(0,0,0,.3);
display:none;
line-height:65px;
text-align:center;
cursor:pointer;
}
#renGongImg .cover .delbtn {
color:#fff;
font-size:20px;
}
#renGongImg .imageDiv:hover .cover {
display:block;
}
#renGongImg .addImages {
display:inline-block;
width:65px;
height:65px;
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
border:1px dashed darkgray;
background:#3d4552;
position:relative;
overflow:hidden;
margin:10px;
}
#renGongImg .text-detail {
text-align:center;
}
#renGongImg .text-detail span {
font-size:30px;
}
#renGongImg .file {
position:absolute;
top:0;
left:0;
width:65px;
height:65px;
opacity:0;
}
html
<div id="renGongImg" class="bord-top pad-ver" style="margin-top:10px;">
<form method="post" action="" id="passForm" enctype="multipart/form-data" multipart="">
<div id="Pic_pass">
<div class="picDiv">
<div class="addImages">
<input type="file" class="file" id="fileInput" 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>
</form>
</div>
js
$("#renGongImg .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'><span class='delbtn'>删除</span></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 = '65px';
imgObjPreview.style.height = '65px';
//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 src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
推荐阅读