在 contentEditable 元素中拖放事件 [英] Drag and drop event in a contentEditable element

查看:22
本文介绍了在 contentEditable 元素中拖放事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 contentEditable 元素中放置东西时(拖动后)会触发什么事件?

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

我说的是普通的拖放,而不是 HTML5 拖放(任何元素都可以拖动);用例很简单:

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:

  • 页面上有一个contentEditable div,用作编辑器
  • 用户从当前页面或另一个页面或另一个浏览器的窗口拖放一些 HTML(因此实际上没有任何源"对象的概念:源可以来自浏览器外部)
  • 需要通知我内容已被放入 contentEditable div,以便我可以对其进行操作(清理它)

我可以轮询 div 以查看是否有任何不干净的地方,但它既昂贵又丑陋";肯定有一个事件会在发生掉落时触发......?

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...?

推荐答案

我在编写 tinyMCE 插件时遇到了同样的问题.我发现在 contentEditable 区域中跟踪元素拖放的最佳方法是监听 contentEditable 元素上的DOMNodeInserted"事件.

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.

请注意,该元素在执行放置时由 contentEditable 元素触发,因此其目标属性设置为该元素.您可以通过检查 event.originalEvent.target 属性来检索移动的元素.

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
      }
});

这篇关于在 contentEditable 元素中拖放事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆