Determine what is being dragged from dragenter & dragover events

前端 未结 9 1946
梦毁少年i
梦毁少年i 2020-12-04 17:35

I\'m trying to use the HTML5 draggable API (though I realize it has its problems). So far, the only showstopper I\'ve encountered is that I can\'t figure out a way to determ

9条回答
  •  抹茶落季
    2020-12-04 18:01

    A (very inelegant) solution is to store a selector as a type of data in the dataTransfer object. Here is an example: http://jsfiddle.net/TrevorBurnham/eKHap/

    The active lines here are

    e.dataTransfer.setData('text/html', 'foo');
    e.dataTransfer.setData('draggable', '');
    

    Then in the dragover and dragenter events, e.dataTransfer.types contains the string 'draggable', which is the ID needed to determine which element is being dragged. (Note that browsers apparently require data to be set for a recognized MIME type like text/html as well in order for this to work. Tested in Chrome and Firefox.)

    It's an ugly, ugly hack, and if someone can give me a better solution, I'll happily grant them the bounty.

    Update: One caveat worth adding is that, in addition to being inelegant, the spec states that all data types will be converted to lower-case ASCII. So be warned that selectors involving capital letters or unicode will break. Jeffery's solution sidesteps this issue.

提交回复
热议问题