简体   繁体   中英

How to set custom data on html drag and drop

I'm trying to set a custom data which is an HTML element on my drag event. So far I did this:

element.addEventListener('dragstart', event => {
  event.dataTransfer.setData('custom-data', document.querySelector('.the-element')
})

dropzone.addEventListener('drop', event => {
  const data = event.dataTransfer.getData('custom-data') // this is empty
})

Is there a way to do this?

I already tried to do JSON.stringify on the element before passing it to the drag event. but JSON.stringify does not work on HTMLElement object

This reference from mdn says it is possible to use custom data

According to this MDN reference , you can specify the data type text/html and pass a well-formed HTML string. If you want to use an existing element in the DOM, you could pass its outerHTML string property.

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