实现效果:
代码实现:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./font_4718460_gwu8lpmmfps/iconfont.css">
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* a{
text-decoration: none;
color: #606266;
font-size: 14px;
} */
.upload{
padding: 20px 10px;
}
input{
display: none;
}
label{
display: block;
width: 80px;
height: 30px;
background-color: #409eff;
color: #fff;
text-align: center;
font-size: 12px;
line-height: 30px;
border-radius: 5px;
}
.upload-tip{
padding: 5px 0;
font-size: 12px;
color: #606266;
}
.upload-message li{
cursor: pointer;
position: relative;
height: 30px;
width: 400px;
padding: 5px 0 5px 18px;
color: #606266;
}
li::before{
content: '';
position: absolute;
top: 8px;
left: 0;
width: 14px;
height: 14px;
background-image: url(./image/文件.png);
background-size: cover;
}
li .close{
content: '';
position: absolute;
top: 8px;
right: 5px;
width: 14px;
height: 14px;
background-image: url(./image/对号.png);
background-size: cover;
}
.upload-message li:hover .close{
background-image: url(./image/取消.png);
}
.upload-message li:hover{
background-color: #f5f7fa;
color: #409eff;
}
</style>
</head>
<body>
<div class="upload">
<label><input type="file" id="file-upload">点击上传</label>
<p class="upload-tip">只能上传jpg/png文件,且不超过500kb</p>
<ul class="upload-message">
<!-- <li>'55555555' <span class="close"></span></li> -->
</ul>
</div>
<script>
const inp=document.querySelector('#file-upload')
const upmessages=document.querySelector('.upload-message')
inp.addEventListener('change',function(e){
console.log(e.target.files[0]);//文件名
// 1.文件大小
const file=e.target.files[0]
// 500kb转换为字节
if(file.size > 500 * 1024 ){
alert('文件大小不能超过500kb')
return
}
// 2.文件类型
if(!file.type.match('image/jpg') && !file.type.match('image/png')){
alert('只能上传jpg/png文件')
return
}
// 3.添加文件到页面
const newli=document.createElement('li')
newli.innerHTML=file.name + '<span class="close"></span>'
upmessages.appendChild(newli)
// 4.点击删除
const closes=document.querySelectorAll('.close')
closes.forEach(item=>{
item.addEventListener('click',function(e){
const content=e.target.parentElement
upmessages.removeChild(content)
})
})
})
</script>
</body>
</html>