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