問題描述
我能否提供一個很好的HTML5 文件拖放 實現示例?如果從外部應用程序(Windows 資源管理器)拖放到瀏覽器窗口,源代碼應該可以工作.它應該適用于盡可能多的瀏覽器.
Can I kindly ask for a good working example of HTML5 File Drag and Drop implementation? The source code should work if drag and drop is performed from external application(Windows Explorer) to browser window. It should work on as many browsers as possible.
我想索要一個有很好解釋的示例代碼.我不想使用第三方庫,因為我需要根據自己的需要修改代碼.代碼應基于 HTML5 和 JavaScript.我不想使用 JQuery.
I would like to ask for a sample code with good explanation. I do not wish to use third party libraries, as I will need to modify the code according to my needs. The code should be based on HTML5 and JavaScript. I do not wish to use JQuery.
我花了一整天的時間尋找好的材料來源,但令人驚訝的是,我沒有找到任何好的材料.我發現的示例適用于 Mozilla,但不適用于 Chrome.
I spent the whole day searching for good source of material, but surprisingly, I did not find anything good. The examples I found worked for Mozilla but did not work for Chrome.
推薦答案
這是一個非常簡單的例子.它顯示一個紅色方塊.如果您將圖像拖到紅色方塊上,它會將其附加到正文中.我已經確認它適用于 IE11、Chrome 38 和 Firefox 32.請參閱 Html5Rocks 文章以獲得更詳細的解釋.
Here is a dead-simple example. It shows a red square. If you drag an image over the red square it appends it to the body. I've confirmed it works in IE11, Chrome 38, and Firefox 32. See the Html5Rocks article for a more detailed explanation.
var dropZone = document.getElementById('dropZone');
// Optional. Show the copy icon when dragging over. Seems to only work for chrome.
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
// Get file data on drop
dropZone.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) {
// finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
document.body.appendChild(img);
}
reader.readAsDataURL(file); // start reading the file data.
}
}
});
<div id="dropZone" style="width: 100px; height: 100px; background-color: red"></div>
這篇關于HTML5、JavaScript:從外部窗口拖放文件(Windows 資源管理器)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!