我有一个输入类型是文件,当我更改此输入的值时,它显示我选择的图像的缩略图(作为背景)。 我的问题是,当我决定第二次更改它时,较旧的图像不会消失。我的代码如下:
document.addEventListener("DOMContentLoaded", function(event) {
const inputLocalFont = document.getElementById("product-image");
inputLocalFont.addEventListener("change", previewImages, false);
function previewImages() {
let fileList = this.files;
let anyWindow = window.URL || window.webkitURL;
for (let i = 0; i < fileList.length; i++) {
let objectUrl = anyWindow.createObjectURL(fileList[i]);
const thumbnail = document.getElementById("thumbnail");
let image = document.createElement("div");
thumbnail.append(image);
let thumbnailDiv = document.querySelectorAll("#thumbnail div");
thumbnailDiv[i].style.backgroundImage="url("+objectUrl+")";
window.URL.revokeObjectURL(fileList[i]);
}
let activeThumb= Array.from(document.querySelectorAll("#thumbnail div"));
const handleClick = (e) => {
activeThumb.forEach(node => {
node.classList.remove("active");
});
e.currentTarget.classList.add("active");
}
activeThumb.forEach(node => {
node.addEventListener("click", handleClick)
});
}
});
&#13;
#thumbnail {
margin-top: 20px;
}
#thumbnail div{
height: 150px;
width: 150px;
background-size: cover;
background-position: center center;
float: left;
margin-right: 10px;
margin-bottom: 10px;
border-radius: 7px;
cursor: pointer;
border: 3px solid #E7E7E7 ;
}
#thumbnail div.active{
border: 3px solid #9BC2EA ;
}
&#13;
<input id="product-image" type="file" multiple>
<div id="thumbnail" class=""></div>
&#13;
答案 0 :(得分:1)
将const thumbnail = document.getElementById("thumbnail");
移到该循环之外和之上。然后在你的循环之前做thumbnail.innerHTML = ''
。您只是追加并且永远不会清除元素内容。