拖拽文件至浏览器实现图片上传功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
.name {
display: block;
width: 100px;
height: 100px;
overflow: hidden;
border: 2px solid #d8d4d4;
border-radius: 2px;
border-radius: 8px;
position: relative;
}
.name::before {
content: '';
position: absolute;
width: 4px;
height: 60px;
left: 50%;
margin-left: -2px;
top: 50%;
margin-top: -30px;
background-color: #d8d4d4;
border-radius: 2px;
}
.name::after {
content: '';
position: absolute;
height: 4px;
width: 60px;
left: 50%;
margin-left: -30px;
top: 50%;
margin-top: -2px;
background-color: #d8d4d4;
border-radius: 2px;
}
#upload {
width: 100%;
height: 100%;
position: absolute;
z-index: 2;
}
</style>
</head>
<body>
<label class="name" for="file">
<input name="file" style="opacity: 0;" type="file" id="upload">
</label>
</body>
<script>
let files = []
const input = document.querySelector("#upload");
input.addEventListener('change', function () {
// 通过onchange事件获取files,函数要使用function定义,箭头函数this指向父级作用域
files = this.files;
}, false);
input.addEventListener('change', (e) => {
// 这个本质还是通过Dom获取文件
files = e.target.files;
console.log(files, 'files')
console.log(e, 'files')
}, false);
</script>
</html>