javascript - 拖拽多张图片上传,为什么图片名字和图片对不上?
迷茫
迷茫 2017-04-11 11:38:50
[JavaScript讨论组]

如题,我当我拖拽超过2张图片的时候,名字和图片就对不上了,哪出错了呢?

HTML:

<p class="wrap">
    <p class="drop-box">请拖拽上传</p>
    <ul class="img-list"></ul>
</p>

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;
            }
        }
    }
}
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号