我正在构建一个chrome扩展程序,它允许用户拖放文件并将其保存到服务器。从扩展中我在页面中注入了div
元素,当我删除图像文件时,浏览器在整个页面上显示图像。在扩展中未检测到drop
事件,但如果我有一个带有类型文件的输入元素,并且如果我将该文件放在该元素上,则会检测到change
事件。
不确定如何从扩展程序中检测drop
事件。任何帮助表示赞赏。
contentScript.js文件
//building the Dropzone Div
var dropdiv = $("<div>", {
id :"sforce-dz-dropZone",
class : "sforce-dz-dropZonebg"
}).text('Add you\'re files here');
//injecting the drop div in the page
$("input[name=attachFile]").after(dropdiv);
//adding 'drop' event listener to the div.
//This is not getting logged at all.
$("#sforce-dz-dropZone").on('drop', function(e){
e.preventDefault();
e.stopPropagation();
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
console.log('the file name is '+ f.name);
}
});
//Adding another event. click, just to see if the events are getting triggered.
//When clicked on the div the console is logging the below string.
$("#sforce-dz-dropZone").on('click',function(){
console.log('clicked');
});
清单文件
{
"name": "name",
"version": "0.0.1",
"manifest_version": 2,
"description": "text",
"author": "someone",
"content_scripts": [
{
"matches" : ["https://*.mysite.com/*"],
"js" : ["jquery.js","contentScript.js"],
"css" : ["sforce-dz.css"]
}
],
"permissions": [
"cookies",
"unlimitedStorage"
]
}
答案 0 :(得分:12)
这是处理拖放的一个非常令人困惑的部分。您希望只使用drop
等来监听click submit mouseOver
事件。但除非它还有dragOver
事件,否则它将无效。
“如果没有dragOver事件处理程序,则使用dragOver事件的默认事件处理程序,因此不会触发drop事件。” Answer Here
/* events fired on the drop targets */
document.addEventListener("dragover", function( event ) {
// prevent default to allow drop
event.preventDefault();
});
document.addEventListener("drop", function( event ) {
// prevent default action (open as link for some elements)
event.preventDefault();
console.log('dropped');
});
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
答案 1 :(得分:0)
dropdiv.on('dragover', function (e) {
return false;
});
当鼠标位于我们的落差区域上方时,您必须返回“false”。
这种方式实现了对源的过滤。
我建议你阅读David Flanagan写的一本书:“JavaScript:The Definitive Guide”