HTML5 Drag Ghost Image Flying Back Prevention

I am creating a sorted list that uses HTML5 drag and drop. It works well, but I have an unpleasant problem when it comes to a ghostly image. The ghostly image always wants to return to the place from where it was. As a result, if the position of the list item changes, the ghost image will revert to the wrong list item.

Ideally, the ghost image should not be displayed at all after the event onDragEnd. I tried setting the image to a blank image on dragEnd using

handleDragEnd(e) {
    e.dataTransfer.setDragImage(new Image(0, 0), 0, 0);
    ...

but I think you can use setDragImagein onDragStart.

Is there a way to hide the ghostly image, onDragEndor at least bring it back to the right place?

+6
source share
1 answer

The return effect is the default behavior in Safari, but you can control this default behavior in the HTML you control. You only need to add the dragover event to the zone in which you want to prevent this undo effect and call e.preventDefault () . The only limitation: you cannot control when the user drags an item from the browser or frame that you control.

But something like this gets rid of the problem you are describing:

var draggedId;
var img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAO0lEQVR42u3OMQ0AMAgAsGFiCvCvDQeggoSjVdD4lf0OC0FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBwR0DX1VWkeseHpAAAAAASUVORK5CYII=";

document.getElementById('a').ondragstart = dragstart_handler;
document.getElementById('b').ondragstart = dragstart_handler;

document.ondragover = (e) => {
  if (draggedId === "a") {
    e.preventDefault();
  }
}

function dragstart_handler(e) {
  draggedId = e.target.id;
  e.dataTransfer.setDragImage(img, 0, 0)
}
div {
  cursor: pointer;
}

div:hover {
  color: blue;
}
<div id=a draggable=true>
  This element won't revert on dragend.
</div>

<div id=b draggable=true>
  This one will revert.
</div>
Run codeHide result

+1
source

Source: https://habr.com/ru/post/1672018/


All Articles