创建
2023年03月23日
一、拖动 Drop 创建 File
- Html
- Css
- JavaScript
<div id="dropbox"> 将文件拖放至此 </div>
#dropbox{
width: 200px;
height: 200px;
background: red;
text-align: center;
line-height: 200px;
}
const dropbox = document.getElementById("dropbox");
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
const { dataTransfer: { files}} = e;
handleFiles(files);
}
function handleFiles(files){
console.log(files)
}
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
二、显性 Input 创建 File
- Html
- Css
- JavaScript
<input type="file" multiple id="show-input"></input>
const input = document.getElementById("show-input");
function handleFiles(e){
const { target:{files} } = e;
console.log(files)
}
input.addEventListener("change",handleFiles,false);
三、隐形 Input 创建 File - Label
- Html
- Css
- JavaScript
<input type="file" multiple id="fileElem" style="display: none" />
<label for="fileElem">上传</label>
const fileElem = document.getElementById("fileElem");
const fileSelect = document.getElementById("fileSelect");
function handleFiles(e){
const { target:{files} } = e;
console.log(files)
}
fileElem.addEventListener("change",handleFiles,false);
四、隐形 Input 创建 File - Button
- Html
- Css
- JavaScript
<input type="file" multiple id="fileElem" style="display: none" />
<button id="fileSelect">上传</button>
const fileElem = document.getElementById("fileElem");
const fileSelect = document.getElementById("fileSelect");
function handleFiles(e){
const { target:{files} } = e;
console.log(files)
}
fileElem.addEventListener("change",handleFiles,false);
fileSelect.addEventListener("click",function(){
if (fileElem) {
fileElem.click();
}
},false);