【问题标题】:drag drop than removing files拖放比删除文件
【发布时间】:2021-10-29 00:24:50
【问题描述】:

我使用 javascript 来拖放多个文件。比我展示这些图像。以下是完全可运行的,没有错误

需要帮助:我也希望能够删除这些图像。请看下面的附图,我想在图像的右上角创建 [x] 按钮。如果单击 [x],它将根据您单击的 [x] 删除图像。关闭在下面的下拉功能中

以下是我目前的 javascript。在 drop 函数中需要帮助

        var dropZone = document.getElementById('dropZone');
        var details = document.querySelector('#imgDetail');
    
        ///////////
        // dragover
        ///////////
        dropZone.addEventListener('dragover', function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            document.getElementById('dropZone').classList.add("hoverActive");
        });
    
        /////////////
        //drag leave 
        /////////////
        dropZone.addEventListener('dragleave', function (e) {
            document.getElementById('dropZone').classList.remove("hoverActive");
        });
    
        ////////////
        // drop file
        ////////////
        dropZone.addEventListener('drop', (e) => {
            document.getElementById('dropZone').classList.remove("hoverActive");
            document.getElementById('BackgroundText').style.visibility = "hidden";
            e.stopPropagation();
            e.preventDefault();
    
            details.innerHTML = '';
            var files = e.dataTransfer.files;
    
            Object.values(files).forEach((file) => {
                var reader = new FileReader();
    
                reader.onloadend = () => {
                    //display image
                    var img = document.createElement('img');
                    img.src = reader.result;
                    img.style.paddingRight = 5;
                    img.width = 150;
                    img.height = 150;
                    img.border = 2;
    
                    var div = document.getElementById('imageHold')
                    div.appendChild(img);
    
                    //create button
                    div.innerHTML += '<button id="btn" name="btn">X</button>';
    
                    //display file name
                    details.innerHTML += `<p>Name: ${file.name}<p>';
    
                    //details.innerHTML += <p>Size: ${bytesToSize(file.size)}</p>`;
                };
                reader.readAsDataURL(file);
            });
        });
    
        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
        }
    
    
      #dropZone
    {
      border: 2px dashed gray;
      height: 200px;
      width: auto;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    #dropZone header{
      font-size: 20px;
      font-weight:bold;
    }

.hoverActive{
 border: 2px dashed darkred !important;
}
   <br /><br />

    <div class="container">
        <div class="row">
            <div>
                <div id="dropZone">
                    <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
                    <header id="BackgroundText">Drag & Drop to Upload File</header>
                    <div id="imageHold" style="float:left;">
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div id="imgDetail">test</div>

html代码

【问题讨论】:

    标签: javascript html jquery drag-and-drop


    【解决方案1】:

            var dropZone = document.getElementById('dropZone');
            var details = document.querySelector('#imgDetail');
        
            ///////////
            // dragover
            ///////////
            dropZone.addEventListener('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
                e.dataTransfer.dropEffect = 'copy';
                document.getElementById('dropZone').classList.add("hoverActive");
            });
        
            /////////////
            //drag leave 
            /////////////
            dropZone.addEventListener('dragleave', function (e) {
                document.getElementById('dropZone').classList.remove("hoverActive");
            });
        
            ////////////
            // drop file
            ////////////
            dropZone.addEventListener('drop', (e) => {
                document.getElementById('dropZone').classList.remove("hoverActive");
                document.getElementById('BackgroundText').style.visibility = "hidden";
                e.stopPropagation();
                e.preventDefault();
        
                details.innerHTML = '';
                var files = e.dataTransfer.files;
        
                Object.values(files).forEach((file) => {
                    var reader = new FileReader();
        
                    reader.onloadend = () => {
                        //create frame elem section
                        let dv = document.createElement('div');
                        dv.style.cssText = `
                            display: inline-block;
                            position: relative; 
                            width: 150px; 
                            height: 150px; 
                            border: 1px #ddd solid;
                            margin-right: 5px;
                        `;
    
                        //create image elem
                        var img = document.createElement('img');
                        img.src = reader.result;
                        // optional 100%
                        // img.style.width = "100%"; 
                        img.style.width = "150px";
                        img.style.height= "150px";
                        
                        //add img to frame 
                        dv.append(img);
    
                        //create btn remove
                        let btn = document.createElement('button');
                        btn.innerHTML = "x";
                        btn.style.cssText = `
                            position: absolute; 
                            right: 2px; 
                            top:2px;
                        `;
        
                        //add btn to frame 
                        dv.append(btn);
    
                        //set frame to target elem
                        document.getElementById('imageHold').append(dv);
                        
                        //set event btn and exec remove frame
                        btn.addEventListener('click', e => {
                            e.target.parentElement.remove();
                        });
                        
        
                        //display file name
                        details.innerHTML += `<p>Name: ${file.name}<p>';
        
                        //details.innerHTML += <p>Size: ${bytesToSize(file.size)}</p>`;
                    };
                    reader.readAsDataURL(file);
                });
            });
        
            function bytesToSize(bytes) {
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if (bytes == 0) return '0 Byte';
                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
            }
        
        
          #dropZone
        {
          border: 2px dashed gray;
          height: 200px;
          width: auto;
          border-radius: 5px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
        }
        #dropZone header{
          font-size: 20px;
          font-weight:bold;
        }
    
    .hoverActive{
     border: 2px dashed darkred !important;
    }
       <br /><br />
    
        <div class="container">
            <div class="row">
                <div>
                    <div id="dropZone">
                        <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
                        <header id="BackgroundText">Drag & Drop to Upload File</header>
                        <div id="imageHold" style="float:left;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    
        <div id="imgDetail">test</div>

    【讨论】:

      【解决方案2】:

      Demo Page

      HTML:

      div.innerHTML += '<button id="btn" name="btn" onclick=removeImage_and_btn(this)>X</button>';
      

      您可以使用previousSibling 来获取上一个元素

      JS:

      function removeImage_and_btn(el){        
          if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back 
              var el = el.previousSibling;
          }
          if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
              el.previousSibling.remove();
              el.remove();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多