简体   繁体   中英

Drag & drop set custom HTML as drag image

Is it possible to somehow set my custom html object to event.dataTransfer.setDragImage(myCustomHtml,0,0) ?

I tried like this

var x=$doc.getElementById("row_selected_notification");
event.dataTransfer.setDragImage(x, 100, 100);

but it didn't work.

As I'm doing this through Java, I'm using native methods so jQuery is not an option for me.

You can either create a custom element on drag or use an existing element. If you are crating an element you have to make sure it is not visible after adding it to the DOM. I've just added a negative top value to the create element to hide it, but i am sure that there are other ways to fix this as well.

Here is an example with one existing element and one that will be created.

 var foo = document.getElementsByClassName("drag-me").item(0), bar = document.getElementsByClassName("drag-me").item(1); // Drag foo and create custom element. foo.addEventListener("dragstart", function(e) { var elem = document.createElement("div"); elem.id = "drag-ghost"; elem.textNode = "Dragging"; elem.style.position = "absolute"; elem.style.top = "-1000px"; document.body.appendChild(elem); e.dataTransfer.setDragImage(elem, 0, 0); }, false); // Drag bar and use foo as ghost image bar.addEventListener("dragstart", function(e) { e.dataTransfer.setDragImage(foo, 0, 0); }, false); // Let's remove the created ghost elem on dragend document.addEventListener("dragend", function(e) { var ghost = document.getElementById("drag-ghost"); if (ghost.parentNode) { ghost.parentNode.removeChild(ghost); } }, false); 
 .drag-me { width: 100px; padding: 30px 0; text-align: center; color: white; display: inline-block; } .drag-me:nth-child(1) { background-color: green; } .drag-me:nth-child(2) { background-color: red; } #drag-ghost { width: 200px; height: 200px; background-color: yellow; } 
 <div class="drag-me" draggable="true">Drag Me Foo</div> <div class="drag-me" draggable="true">Drag Me Bar</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM