在实际开放中难免不会遇见file 多图上传同事修改
<input type="file" multiple="multiple"> 提供了multiple这个属性,可以拖动选择多上图片进行上传
也可以通过formData 对象对files对象的值进行 [ ].slice.call( files )转成; 来修改files 对象里面的内容 在append进行修改!
缺点:如果第一次多选然后断开选择第二次的时候file 对象会被新的一次选择覆盖。
原生获取file对象: var file = document.getElementById("file").files;
jQuery获取file对象想: var file = $("#file").prop("files")[0];
打印效果:

在思考点击一下上传一张图片的话,就要动态生成<input type="file" >标签,并点击一个按钮。
先把file 放一个div 中。上html代码
<div class="imgBox">
<div id="uploadDiv" class="click-file">图片上传</div>
<div id="fileDiv" class="shengtai"></div>
</div>
<div class="imgsBox">
//存放 图面显示的盒子
</div>
下面我们就对利用js 来处理对图片的增删行为
首先引入jQ------引入不上了
这里我的思路是做一个按钮,在点击按钮的时候触发file的change事件
<script type="text/javascript">
$(function(){
//add picture IMG
$("#uploadDiv").on("click",function(){
//display:none ==>让file 隐藏不让图片下显示那么多
var upFile = `<input type="file" id="upFile" name="files" style="display:none;" />`
$("#fileDiv").append($(upFile));
$("#upFile").bind('change',function(e){
var files = $("#upFile").prop("files")[0];
console.log(files);
var reader = new FileReader();
reader.readAsDataURL(files);
reader.onload = function(e){
$(".imgsBox").append(`<div class="imgDiv">
<span class="span">x</span>
<img src="${this.result}" class="img">
</div>`);
}
// 添加完成后一定要清除id
$(this).removeAttr('id');
})
$("#upFile").click();
})
//dele picture IMG
$(".imgsBox").on("click",".span", function(){
var $this = $(this);
var $box = $this.parent();
var index = $box.index();
console.log($box);
var $fileElem = $("#fileDiv").children().eq(index);
$box.remove();
$fileElem.remove();
})
})
</script>
基本功能完成了 现在把页面美化一下
CSS 样式如下:
<style type="text/css" media="screen">
.imgBox{
position: relative;
}
.click-file{
margin-top:20px;
border:1px solid #ddd;
border-radius: 5px;
height:40px;
width:100px;
text-align: center;
line-height: 40px;
cursor:pointer;
}
.click-file:hover{
background: #ddd;
color:#fff;
}
.imgsBox{
margin-top:20px;
}
.imgDiv{
width:200px;
padding:10px;
display: inline-block;
border:1px solid #ddd;
position: relative;
margin:10px;
}
.imgDiv .span{
position:absolute;
right:-6px;top:-6px;
width:12px;height:12px;
text-align: center;
line-height: 12px;
border-radius: 50%;
border:1px solid #ddd;
cursor: pointer;
}
.imgDiv img{
width:100%;
}
</style>


基本思路 --
网友评论