js多图上传展示和删除

html部分

 <button class="btn btn-info" for="file">请选择文件</button>
<input type="file" id="file" name="file" multiple='multiple' class="hidden"  onchange="showPicture(this)"/>
<div id="imgBox" class="form-group">

js部分

var imgSrc = []; //图片路径
    var imgFile = []; //文件流
    var imgName = []; //图片名字
    var imgBox=$('#imgBox');
    function showPicture(imgF){
        var fileList=imgF.files;
        for(var i = 0; i < fileList.length; i++){
                    var imgSrcI = getObjectURL(fileList[i]);
                    imgName.push(fileList[i].name);
                    imgSrc.push(imgSrcI);
                    imgFile.push(fileList[i]);
            }
            addNewContent(imgBox);
  }
//图片展示
function addNewContent(obj) {
    $(imgBox).html("");
    for(var a = 0; a < imgSrc.length; a++) {
        //console.log(imgSrc);
        var oldBox = $(obj).html();
        $(obj).html(oldBox + '<div class="imgContainer col-sm-4"><img width="100%" class="img-rounded" title=' + imgName[a] + ' alt=' + imgName[a] + ' src=' + imgSrc[a] + ' ><span onclick="sc('+a+')">删除</span></div>');
    }
}
//图片预览路径
function getObjectURL(file) {
    var url = null;
    if(window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if(window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if(window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}
//删除
function sc(index){
    
   imgSrc.splice(index,1);
   index='';
   addNewContent(imgBox);
   
}

效果如下

posted @ 2018-04-13 23:44  xue11hua  阅读(572)  评论(0编辑  收藏  举报