Controlling the appearance of the HTML5 drag and drop effect

六眼飞鱼酱① 提交于 2019-11-27 22:00:05

I think .setDragImage(element, x, y); might be what you are looking for.

function handleDragStart(e) {
    var dragIcon = document.createElement('img');
    dragIcon.src = 'http://...';
    dragIcon.width = 100;
    e.dataTransfer.setDragImage(dragIcon, x, y);
}

this.addEventListener('dragstart', handleDragStart, false);

Example here: jsfiddle.net/cnAHv/

Unfortunately, it looks like the spec was built to favor consistent native behavior over in-browser customization.

We did a bunch of research and summarized our findings here:

https://www.inkling.com/engineering/native-html5-drag-drop/

The long and short, though, is that using a helper (like jQuery UI) or rolling your own is generally preferable if you need to do anything sophisticated.

Still, if you'd really like to use the native behavior and setDragImage() isn't adequate, there are a few alternatives.

One particularly extravagant approach could involve hijacking the renderer to create a screenshot (!) of the element as you‘d like it to be styled, and then inserting it via a data URI.

See: http://cburgmer.github.io/rasterizeHTML.js/jsconfeu2013/#/step-4

A saner approach would be to simply absolutely position a ghost element to follow the mouse. But that takes us back to writing code that re-implements core parts of drag behavior outside of the API.

Mohammad Areeb Siddiqui

According to this question on StackOverflow, we cannot change the style of the draggable object while dragging it but we can set a drag image. This will cause a image to appear while dragging the ghost object.

event.dataTransfer.setDragImage(document.getElementById('div2'),50,50);

Explanation:

on dataTransfer we call a setDragImage() function in which we pass the ID of the div and give the position of where the image will appear when we will start dragging it.

See more about dataTransfer here: Mozilla Developers - DataTransfer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!