1 回答
TA贡献1802条经验 获得超5个赞
问题是当您在放置事件中分配文件时,文件输入上的事件侦听器不会触发。fileInput.addEventListener("change", () => {
将该代码嵌入到函数中,您可以在ondrop事件结束时调用它来完成预期的行为。
const dropContainer = document.getElementById("dropContainer");
const fileInput = document.getElementById("fileInput");
const fakeButton = document.getElementById("fakeButton");
const fileText = document.getElementById("fileText");
function SetFileName() {
if (fileInput.value) {
fileText.innerHTML = fileInput.value.match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[1];
} else {
fileText.innerHTML = "no file selected";
}
};
fakeButton.addEventListener("click", () => {
fileInput.click();
});
// dragover and dragenter events need to have 'preventDefault' called
// in order for the 'drop' event to register.
// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets
dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
evt.preventDefault();
};
dropContainer.ondrop = function(evt) {
// pretty simple -- but not for IE :(
fileInput.files = evt.dataTransfer.files;
// If you want to use some of the dropped files
const dT = new DataTransfer();
dT.items.add(evt.dataTransfer.files[0]);
fileInput.files = dT.files;
SetFileName()
};
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<div id="dropContainer">
Drag and drop a file
<br>
or
<br>
<input type="file" id="fileInput" hidden="hidden" />
<button id="fakeButton">Select a file</button>
<span id="fileText">No file Selected</span>
</div>
</body>
</html>
添加回答
举报