3

在一个表单中,我想让用户一张一张地上传多张图片,并让他们通过点击一个x按钮来删除每张图片:

这是我的 javascript/jQuery,它将 Base64 图像预览添加到 DOM:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      let image = new Image();
      image.src = `${e.target.result}`;
      image.className = "img-thumbnail add-image-thumb";          
      let closeBtn = `<button type="button" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span> </button>`;
      $('#images-to-upload').append(image);
      $('#images-to-upload').append(closeBtn);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function () {
  readURL(this);
});

和 html 部分:

 <div id="images-to-upload" class="mb-3"> </div>
 <div class="input-group mb-3">          
    <div class="custom-file">
      <input type="file" class="custom-file-input" id="imgInp" >
      <label class="custom-file-label" for="image-input"></label>
    </div>
    
  </div>
  <small class="form-text text-muted">Upload one or more images</small>

<br>

CSS:

.add-image-thumb{
  max-height: 64px;
  margin: 10px;
  padding: 5px;
}

这适用于一个图像,但对于多个图像,都x转到页面的右侧。

问题是如何将x按钮放在每个图像的左上角。我不能用 Base64 图像构建一个 div,否则我可以通过 CSS 来实现。

4

1 回答 1

3

我不能用 Base64 图像构建一个 div,否则我可以通过 CSS 来实现。

在图像周围包裹一个 div

  let wrapper = $('<div class="image-wrapper" />');
  $('#images-to-upload').append(wrapper) 
  $(wrapper).append(image);
  $(wrapper).append(closeBtn);

使用下面的 CSS

.image-wrapper {
   display: inline-block;
   position: relative;
}
.image-wrapper button {
   position: absolute;
   top: 0;
   right: 0;
 }
于 2020-09-24T03:07:36.903 回答