最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Drag & drop a file anywhere on a page - Stack Overflow

programmeradmin0浏览0评论

I have the following code:

<input type="file" name="file" id="file">

You can click on it to select a file. But alternatively you can drag a file and drop it on the Select file button. But you have to exactly hold the cursor above the button when dropping the file. Otherwise it won't work.

There are ways to make the button or the drop zone bigger.

But I'd like to make the entire page a drop zone. So I can drop the file anywhere on the entire page and still id="file" will „receive“ it.

I just need the functionality itself. I don't need a hover animation or something like this.

How is it possible?

I have the following code:

<input type="file" name="file" id="file">

You can click on it to select a file. But alternatively you can drag a file and drop it on the Select file button. But you have to exactly hold the cursor above the button when dropping the file. Otherwise it won't work.

There are ways to make the button or the drop zone bigger.

But I'd like to make the entire page a drop zone. So I can drop the file anywhere on the entire page and still id="file" will „receive“ it.

I just need the functionality itself. I don't need a hover animation or something like this.

How is it possible?

Share Improve this question asked Dec 5, 2022 at 10:03 DavidDavid 3,3585 gold badges29 silver badges68 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

I finally ended up with this fully working code:

<script>
document.addEventListener('dragover', (e) => {
    e.preventDefault()
});
document.addEventListener('drop', (e) => {
    document.getElementById('file').files = e.dataTransfer.files;
    e.preventDefault()
});
</script>

<input type="file" name="file" id="file">

Additionally, I added document.getElementById('file').onchange(); to the drop event listener because there's an onchange in my input that wouldn't get called this way.

To make the entire page a drop zone, you can add an event listener to the body element and define the event handler function.

This function will be called when a file is dropped onto the page. You can then use the target element from the event object to access the file input element and set the file accordingly.

Example:

const dropZone = document.querySelector('body');

dropZone.addEventListener('drop', (e) => {
  const fileInput = document.getElementById('file');
  fileInput.files = e.dataTransfer.files;
});

You need to add an event to the entire page in JS (body), that will handle the drop.

Maybe check this article : https://www.smashingmagazine./2018/01/drag-drop-file-uploader-vanilla-js/

发布评论

评论列表(0)

  1. 暂无评论