Determine what is being dragged from dragenter & dragover events

前端 未结 9 1945
梦毁少年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 17:58

    Given the current spec, I don't think there is any solution that isn't a "hack". Petitioning the WHATWG is one way to get this fixed :-)

    Expanding on the "(very inelegant) solution" (demo):

    • Create a global hash of all elements currently being dragged:

      var dragging = {};
      
    • In the dragstart handler, assign a drag ID to the element (if it doesn't have one already), add the element to the global hash, then add the drag ID as a data type:

      var dragId = this.dragId;
      
      if (!dragId) {
          dragId = this.dragId = (Math.random() + '').replace(/\D/g, '');
      }
      
      dragging[dragId] = this;
      
      e.dataTransfer.setData('text/html', dragId);
      e.dataTransfer.setData('dnd/' + dragId, dragId);
      
    • In the dragenter handler, find the drag ID among the data types and retrieve the original element from the global hash:

      var types = e.dataTransfer.types, l = types.length, i = 0, match, el;
      
      for ( ; i < l; i++) {
          match = /^dnd\/(\w+)$/.exec(types[i].toLowerCase());
      
          if (match) {
              el = dragging[match[1]];
      
              // do something with el
          }
      }
      

    If you keep the dragging hash private to your own code, third-party code would not be able to find the original element, even though they can access the drag ID.

    This assumes that each element can only be dragged once; with multi-touch I suppose it would be possible to drag the same element multiple times using different fingers...


    Update: To allow for multiple drags on the same element, we can include a drag count in the global hash: http://jsfiddle.net/jefferyto/eKHap/2/

提交回复
热议问题