javascript - 如何为base64图片预览添加关闭按钮?

标签 javascript html jquery css

在一个表单中,我想让用户一张一张地上传多张图片,并让他们通过单击 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 来实现它。

最佳答案

I could not construct a div out of Base64 images, otherwise I could mangage to acheive that through 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;
 }

关于javascript - 如何为base64图片预览添加关闭按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64038913/

相关文章:

javascript - 事件处理程序返回未定义?

javascript - 我的 Greasemonkey 脚本无法安装

javascript - 单击 target_blank 链接后关闭窗口

javascript - Matter.js 创建一个旋转平台

jquery - Primefaces:尝试使用 jquery 和 selectBooleanCheckbox 选择所有复选框

javascript - 未决 promise 后 JSON 输入错误意外结束

php - 默认情况下,WordPress 会在其 JavaScript 中公开基本 URL 吗?

javascript - 如何使用元素符号使用 jquery 制作 slider

html - Bootstrap 导航栏固定大小

javascript - 如何在 javascript 的 eval 函数中添加单引号?