[英]How to add a close button to base64 image preview?
在一种形式中,我想让用户一张一张地上传多张图片,并让他们通过点击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 设法实现它。
我无法用 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.