Javascript 检测 contenteditable 中的粘贴事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8190770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect a paste event in a contenteditable
提问by Rachela Meadows
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?
给定一个内容可编辑的 div。如何检测粘贴事件,防止插入粘贴,以便我可以拦截和清理粘贴以仅包含文本?
I also don't want to lose focus after the paste + sanitize is complete.
我也不想在粘贴 + 消毒完成后失去焦点。
采纳答案by dcro
UPDATE:
更新:
All major browsers now give you access to the clipboard data in a paste event. See Nico Burns's answerfor an example on newer browser and also check out Tim Down's answerif you need to support older browsers.
所有主要浏览器现在都允许您在粘贴事件中访问剪贴板数据。有关较新浏览器的示例,请参阅Nico Burns 的回答,如果您需要支持较旧的浏览器,还可以查看Tim Down 的回答。
You can listen for the onPasteevent on the div to detect the paste. If you just want to disable the paste you can call event.preventDefault()
from that listener.
你可以监听div 上的onPaste事件来检测粘贴。如果您只想禁用粘贴,您可以event.preventDefault()
从该侦听器调用。
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:
然而,捕获粘贴的内容有点困难,因为该onPaste
事件不允许您访问粘贴的内容。处理此问题的常用方法是从onPaste
事件处理程序执行以下操作:
- 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)
- 创建一个虚拟 div 并将其放置在窗口边界之外,以便访问者看不到它
- 将焦点移到这个 div
- 使用 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
- 找到虚拟 div 并获取它的内容
- 清理 HTML 并删除 div
- 将焦点移回原来的 div
- 在原始 div 中插入清理过的内容