HTML disable Drop event, div box child contents ov

2019-06-10 05:31发布

问题:

I followed the drag&drop tutorial online, and test it a little bit on my own. Then I realized a problem: so I dragged image1 to Box A and image2 to Box B, then i'm trying to drag image1 from Box A to Box B, the issue appears. If I drop image1 on the edge of Box B, everything works fine, both images are in the Box B, if I drop image1 on top of image2, image1 disappeared. does anyone know how to prevent this? I want box both image shows in the box no matter how I drop them.

my example link:http://qcn.freeiz.com/VisTool/DnDrp%20Test.htm

Thanks!

回答1:

Learn about event bubbling and understand that ev.target is initially the element the drop event occurred on, not the element you attached the listener to. Check what ev.target is before doing appendChild and ev.preventDefault(). Here is a simple example:

function dragDrop(ev) {
    var eleid = ev.dataTransfer.getData("Text");
    var el = ev.target;
    if (el.id != 'dropzone' && el.id != 'dropzone2') {
        el = el.parentNode;
    }
    el.appendChild(document.getElementById(eleid));
    ev.preventDefault();
}