在contenteditable中检测粘贴事件 [英] Detect a paste event in a contenteditable
问题描述
我也不想在粘贴+清理完成后失去焦点。
更新:
$ b
现在,所有主流浏览器都允许您在粘贴事件中访问剪贴板数据。有关较新浏览器的示例,请参阅 Nico Burns的回答,并查看 Tim Down的答案,如果您需要支持旧浏览器。 您可以侦听div上的 onPaste 事件以检测粘贴。如果您只想禁用粘贴,您可以从该监听器调用 event.preventDefault()
。
然而,由于 onPaste
事件不允许您访问粘贴的内容,所以粘贴的内容有点困难。处理这种情况的常用方法是从 onPaste
事件处理程序执行以下操作:
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屋!