case:本地上传图片后实现预览与删除功能
效果预览
1.html
文件
<div class="upload-box">
<!--多选-->
<input type="file" id="upload-Input" accept="image/*" multiple>
<div class="upload-file">
<div id="imagesContainer"></div>
<button id="upload-btn">
<img src="./add.png" alt="" width="36px" height="36px">
<div class="tips">添加附件</div>
</button>
</div>
</div>
<button class="upload-submit" onclick="submit()">提交</button>
css
文件
input[type="file"] {
display: none;
}
button{
width: 120px;
height: 120px;
background: #FFFFFF;
border: 1px solid #0062FF;
font-size: 16px;
color: #0062FF;
padding: 0;
cursor: pointer;
}
button .tips{
margin-top: 7px;
}
button.upload-submit {
width: 120px;
height: 40px;
margin-top: 20px;
background: #0062FF;
border-radius: 8px;
color: #FFFFFF;
font-weight: 500;
font-size: 14px;
}
.upload-file{
display: flex;
/* flex-wrap: wrap; */
}
.upload-file #imagesContainer{
display: flex;
flex-wrap: wrap;
}
.upload-box{
width: 800px;
background-color: #f9f9f9;
}
.upload-file .upload-item{
width: 120px;
height: 120px;
position: relative;
text-align: center;
line-height: 120px;
margin-right: 10px;
margin-bottom: 10px;
}
.upload-file .upload-item .previewImg{
max-width: 100%;
}
.upload-file .upload-item .delImg{
position: absolute;
right: 0;
top: 0;
cursor: pointer;
}
js
文件
const uploadInput = document.getElementById('upload-Input')
const uploadBtn = document.getElementById('upload-btn')
let files = []
uploadBtn.addEventListener('click', function () {
()
})
uploadInput.addEventListener('change', function (e) {
files = [...e.target.files];
const container = document.getElementById('imagesContainer');
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
// FileReader对象可以异步读取存储在开发者的计算机磁盘上的数据内容,可以使用File对象或Blob对象来指定所要处理的文件或数据。
// 文件读取是异步的,因此我们不能立即访问文件内容。相反,我们需要在onload事件处理函数中处理文件内容。
reader.onloadend = function(event) {
// 当文件读取完成后,onload事件处理函数将被调用
let div = document.createElement('div');
div.classList.add('upload-item');
let img1 = document.createElement('img');
img1.src = reader.result;
// 文件内容可以通过event.target.result访问
img1.classList.add('previewImg');
img1.style.maxWidth = '100%';
let img2 = document.createElement('img');
img2.src = "./del.png";
img2.classList.add('delImg');
img2.style.width = '16px';
img2.style.height = '16px';
img2.setAttribute('data_idx', i)
img2.onclick = handleDel(i)
div.appendChild(img1);
div.appendChild(img2);
container.appendChild(div);
}
if (file) {
reader.readAsDataURL(file);
// readAsDataURL()方法则可以将文件读取为一段以data:url格式的字符串,这段字符串的实质都是Data URI,
}
}
})
// 删除
function handleDel(idx) {
return () => {
const container = document.getElementById('imagesContainer');
const divs = document.getElementsByClassName('upload-item');
const imgdels = document.getElementsByClassName('delImg');
for (let i = 0; i < files.length; i++) {
if(imgdels[i]){
if(idx == imgdels[i].getAttribute('data_idx')){
files.splice(i, 1)
container.removeChild(divs[i]);
}
}
}
}
}
function submit(){
console.log(files.map(item => ))
}