如题,我当我拖拽超过2张图片的时候,名字和图片就对不上了,哪出错了呢?
HTML:
<div class="wrap">
<div class="drop-box">请拖拽上传</div>
<ul class="img-list"></ul>
</div>
CSS:
*{padding:0;margin:0;}
ul { list-style: none; }
li { width: 150px; height: 150px; margin-right: 10px; float: left; }
li img { width: 100%; height: 100%; border-radius: 5px; border: 1px solid #ddd; }
.drop-box { clear: both; width: 200px; height: 200px; line-height: 200px; border: 2px dashed #aaa; margin-bottom: 100px; text-align: center; }
.image{margin-bottom: 10px;}
.title{ text-align: center; }
JS:
var box = document.querySelector('.drop-box');
var flag = false;
var iNow = 0;
box.ondragover = function(e){
e.preventDefault();
this.innerHTML = '请松开鼠标';
}
box.ondragleave = function(){
this.innerHTML = '请拖拽上传';
}
box.ondrop = function(e){
var files = e.dataTransfer.files;
var imgList = document.querySelector('.img-list');
var pList = [];
var item;
var file;
e.preventDefault();
this.innerHTML = '请拖拽上传';
for (let i = 0; i < files.length; i++) {
var p;
var fileReader = new FileReader();
fileReader.readAsDataURL(files[i]);
file = files[i];
p = document.createElement('p');
p.className = "title";
p.innerHTML = file.name;
pList.push(p);
fileReader.onload = function(e){
var url = this.result;
var str = `<li class="item">
<img class="image" src=${url}>
</li>`;
imgList.innerHTML += str;
item = document.querySelectorAll('.item');
if (!flag && pList.length == item.length){
iNow = item.length;
flag = true;
for (let j = 0; j < item.length; j++) {
item[j].appendChild(pList[j]);
}
}else if(flag && pList.length == item.length - iNow){
for (let j = 0; j < pList.length; j++) {
item[iNow + j].appendChild(pList[j]);
}
iNow = item.length;
}
}
}
}