Вопрос

I have a page which has a droppable element a1, as well as a specific element a2 which is sortable. Files dropped into a1 are read and deposited into a sortable list in a2. The upload and sortable scripts are not included in my code below as they are not relevant to the issue.

The problem is that if any file is dropped anywhere into other than a1, the browser will attempt to open the file for display in the browser. This is quite evident with image files..

I have tried to disable everything but a1 with the following code, but this still does not appear to have worked, I'm still getting the unwanted redirect...

I've Googled my butt off here, but it seems there's a lot about adding drag and drop, but very little with respect to preventing drag and drop...

Can someone please tell me what I am doing wrong here with the following code?

<div id="a1"></div>
<div id="a2"></div>
<script>
drop = $("not(#a1)");
drop.droppable("option",{disabled:true, tolerance:"pointer"});
drop.droppable("disable");
drop.on("drop",function(e){
    e.preventDefault();
}
</script>

Many thanks in advance!

Это было полезно?

Решение 3

After enough tinkering I managed to come up with a more suitable solution...

Seeing I'm only really focusing on the prevention of files being dropped into sortable area, I decided to focus on determining the nature of the item being dropped...

drop = $(".all-slides");
drop.on('dragover', function(e){
    e.preventDefault();
});
drop.on('dragenter', function(e){
    e.preventDefault();
});
                                            drop.on('drop', function(e){
    e.preventDefault();
    dt = e.originalEvent.dataTransfer;
    if(dt.types != null && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('application/x-moz-file'))) {
        alert('You cannot upload images here. \nIf you wish to upload files, \nclick on the "Upload Images" button.');
    }
});

Put simply, the drop event listens for any possibility of data transfer, and if there is no data transfer possible, we know it's a DOM element... Otherwise we know it's a file, and we throw the alert...

Другие советы

I created a simple JsFiddle to make it work. Basically you can cancel the event with a handler on the document itself, without worrying about where the file was dropped:

$("#a1").on('drop', function() {
    // your logic here
    alert('dropped on a1!');
});

$(document).on('drop dragover', function(e) {
    e.preventDefault();
});

If you are using an older version of jQuery, you might have to replace the on function with live.

You have used wrong jQuery selector for not.

Try this

drop = $("div").not("#a1");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top