仅将纯文本粘贴到可编辑 div 中
我需要能够允许用户粘贴到可编辑的 div 中(通过用户选择的任何方式:右键单击并粘贴、快捷键等),但我想放弃格式设置,只采用纯文本。
我无法使用文本区域,因为如果由用户启动的事件应用,div 将允许基本格式(粗体和斜体)。
onbeforepaste
事件看起来很有希望,但根据 quirksmode 的说法,支持非常有限,以至于无法使用。
I need to be able to allow a user to paste into an editable div (via whatever the user chooses: right-click and paste, shortcut key, etc), but I want to discard formatting and only take the plain text.
I can't use a textarea since the div will allow basic formatting (bold and italic) if applied by user-initiated events.
The onbeforepaste
event looked promising, but according to quirksmode the support is so limited as to be unusable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这很棘手,但并非不可能。您可以做的事情非常复杂,并且需要一些技巧,可以在 Firefox 2+、IE 5.5+ 和最新的 WebKit 浏览器(例如 Safari 4 或 Chrome)中工作(在旧版本上未经测试)。 TinyMCE 和 CKEditor 的最新版本在其基于 iframe 的编辑器上使用了此技术:
请注意,这仅适用于键盘粘贴事件,不适用于从上下文或编辑菜单粘贴。
paste
事件会更好,但当它触发时,将插入符号重定向到文本区域(至少在某些浏览器中)为时已晚。This is tricky but not impossible. What you can do is quite involved and a bit of a hack that will work in Firefox 2+, IE 5.5+ and recent WebKit browsers such as Safari 4 or Chrome (untested on older versions). Recent versions of both TinyMCE and CKEditor use this technique on their iframe-based editors:
Note that this will only work for keyboard paste events and not pastes from the context or edit menus. The
paste
event would be better but by the time it fires, it's too late to redirect the caret into the textarea (in some browsers, at least).对于 Ctrl+v 我检查了 keyup 上可编辑 div 的内容。您可以修改该事件中的内容。我正在使用 nicedit 文本编辑器。
这不适用于从右键单击粘贴 ->粘贴。
对于“粘贴”,我必须使用
settimeout
修改内容。For Ctrl+v I checked the content of the editable div on keyup. You can modify the content in that event. I was using nicedit text editor.
This did not work for paste from right click-> paste.
For 'paste' I had to modify the content using
settimeout
.也可以使用 javaScript 对其进行攻击。希望这有助于
我此处创建了一个示例
It can also be hacked by using javaScript. Hope this helps
I created an example here
您是否尝试过“粘贴”或“输入”等事件?然后你可以使用正则表达式来删除所有html标签
http://www. hscripts.com/scripts/JavaScript/remove-html-tag.php
有一个关于粘贴事件的讨论,您还应该阅读:
捕获粘贴输入
Did you try the event such as "paste" or "input" ? Then you can use regex to trip all html tag
http://www.hscripts.com/scripts/JavaScript/remove-html-tag.php
There is a discussion on paste event you should also read :
Catch paste input
您可以使用:
execCommand
现在似乎已被弃用。所以要小心。但主要浏览器继续支持它。You can use:
execCommand
seems to be deprecated nowaday. So be careful with it. But main browsers continue to support it.