在contenteditable中检测粘贴事件 [英] Detect a paste event in a contenteditable

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

问题描述

给定一个内容可编辑div。如何检测粘贴事件,防止粘贴被插入,这样我可以拦截和清理粘贴以仅包含文本?



我也不想在粘贴+清理完成后失去焦点。

解决方案

更新:
$ b

现在,所有主流浏览器都允许您在粘贴事件中访问剪贴板数据。有关较新浏览器的示例,请参阅 Nico Burns的回答,并查看 Tim Down的答案,如果您需要支持旧浏览器。 您可以侦听div上的 onPaste 事件以检测粘贴。如果您只想禁用粘贴,您可以从该监听器调用 event.preventDefault()



然而,由于 onPaste 事件不允许您访问粘贴的内容,所以粘贴的内容有点困难。处理这种情况的常用方法是从 onPaste 事件处理程序执行以下操作:


  • 创建一个虚拟div并将其放置在窗口边界外,以便访问者不可见

  • 将焦点移至此div

  • 呼叫清洁工方法使用 setTimeout(sanitize,0)



和您的清理方法:


  • 找到虚拟div并获取它的内容
  • 清理HTML并移除div

  • 将焦点移回原始div

  • 在原始div中插入已消毒的内容


given a content editable div. How can I detect a paste event, prevent the paste from being inserted so can I can intercept and sanitize the paste to include text only?

I also don't want to lose focus after the paste + sanitize is complete.

解决方案

UPDATE:

All major browsers now give you access to the clipboard data in a paste event. See Nico Burns's answer for an example on newer browser and also check out Tim Down's answer if you need to support older browsers.


You can listen for the onPaste event on the div to detect the paste. If you just want to disable the paste you can call event.preventDefault() from that listener.

To capture the pasted content however is a little bit more difficult since the onPaste event does not give you access to the pasted content. The usual way to handle this is to do the following from the onPaste event handler:

  • create a dummy div and place it outside the window boundaries so it's not visible to visitors
  • move the focus to this div
  • call a sanitizer method using a setTimeout(sanitize, 0)

and from your sanitizing method:

  • find the dummy div and get it's contents
  • sanitize the HTML and remove the div
  • move the focus back to the original div
  • insert the sanitized content in the original div

这篇关于在contenteditable中检测粘贴事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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