在容器div内的图像周围填充相等的填充

时间:2017-05-02 08:39:19

标签: javascript html css

我正在研究多文件上传系统。文件上传工作正常。当我决定在文件读取完成之前显示预览div时出现问题。为此我在for循环中创建了一个容器div并尝试插入容器中的图像。问题是容器内的图像周围没有相同的填充。如何解决这个问题?

function handleDragOver(event) {
  event.stopPropagation();
  event.preventDefault();
  event.dataTransfer.dropEffect = 'copy';
  document.getElementById('drop_zone').innerHTML = "";
}

function handleDragLeave() {
  document.getElementById('drop_zone').style.background = 'white';
}

function handleFileSelect(event) {
  event.stopPropagation();
  event.preventDefault();

  var files = event.dataTransfer.files;

  for (var i = 0, file; file = files[i]; i++) {
    if (i >= files.length) {
      break;
    }
    (function(file) {

      var reader = new FileReader();

      var container = document.createElement('div');
      reader.onloadstart = function() {


        container.setAttribute('style', 'background:gray;text-align:center;padding:2px;width:100px;height:100px;margin:8px;float:left;border:1px solid gray;');
        document.getElementById('drop_zone').appendChild(container);

      };

      reader.onloadend = (function(myfile) {

        return function(event) {

          var img = new Image();
          img.src = event.target.result;
          img.width = 100;
          img.height = 100;
          container.style.background = 'white';
          container.style.width = '';
          container.style.height = '';
          container.appendChild(img);


        }

      })(file);


      reader.readAsDataURL(file);
    })(file);




  }


}

function handleFileUpload() {

  var dropZone = document.getElementById('drop_zone');
  dropZone.addEventListener('dragover', handleDragOver, false);
  dropZone.addEventListener('dragleave', handleDragLeave, false);
  dropZone.addEventListener('drop', handleFileSelect, false);

}
handleFileUpload();
<div id="drop_zone" style="width:95%;border:4px dotted gray;float:left;min-height:100px;text-align:center;line-height:100px;color:gray;font-size:25px;">
  Drop files here

</div>

1 个答案:

答案 0 :(得分:1)

#drop_zone的行高设置为100px,这导致了问题。

将图像的行高设置为line-height: 0;