Drag and drop event in a contentEditable element

2019-02-15 09:56发布

问题:

What event is fired when one drops something in a contentEditable element (after dragging)?

I'm talking about plain old drag and drop, NOT HTML5 drag and drop (where any element can be made draggable); the use case is simply:

  • there's a contentEditable div on the page, used as an editor
  • the user drags and drops some HTML from the current page or from another page, or from another browser's window (so there really isn't any concept of "source" object: the source can come from outside the browser)
  • I need to be notified that the content has been dropped into the contentEditable div so that I can act on it (clean it)

I could poll the div to see if anything's there that's not clean, but it's expensive and "ugly"; surely there's an event that fires when a drop occurs...?

回答1:

I faced the same problem while writing a tinyMCE plugin. What I found the best way to track drag and drop of elements in a contentEditable zone is to listen to the 'DOMNodeInserted' event on the contentEditable element.

Note that this element is fired by the contentEditable element when the drop is performed so that its target property is set to this element. You can retrieve the moved element by checking the event.originalEvent.target property.

Be aware that this event is fired once the dropped is finished and that the drop element has been inserted.

$('#editor').bind('DOMNodeInserted', function(event){
      if(event.originalEvent && event.originalEvent.target){
        var target = $(event.originalEvent.target);
        //now you can check what has been moved
      }
});