简体   繁体   中英

setDragImage Doesn't Work In Safari, But Works In Chrome (HTML Drag API)

I am trying to use .setDragImage on an anchor element to customize its image when it is being dragged. For some reason, it works perfectly in Chrome but not in Safari. Here is an example:

 const drag = document.getElementById("drag"); const testEl = document.createElement("div"); testEl.innerText = "Drag Info"; drag.ondragstart = (event)=>{ document.body.appendChild(testEl); event.dataTransfer.setDragImage(testEl, 0, 0); setTimeout(()=>{ testEl.remove(); }, 1); };
 <a id="drag" href="javascript:console.log('clicked')">Drag Me</a>

Notice that when dragging, in Safari a special box with the link is displayed, while in Chrome it correctly says "Drag Info"

It turns out that in order to add a drag image to an element you must set its draggable property equal to true.

Eg

<a href="...">Link</a>

Should be

<a href="..." draggable="true">Link</a>

Fixed example:

 const drag = document.getElementById("drag"); const testEl = document.createElement("div"); testEl.innerText = "Drag Info"; drag.ondragstart = (event)=>{ document.body.appendChild(testEl); event.dataTransfer.setDragImage(testEl, 0, 0); setTimeout(()=>{ testEl.remove(); }, 1); };
 <a draggable="true" id="drag" href="javascript:console.log('clicked')">Drag Me</a>

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