问题描述
根据这里介绍的示例,我有一个基于
拦截粘贴事件,取消粘贴,并手动插入剪贴板的文本表示:。这应该是最可靠的:
- 它可以捕捉各种粘贴(Ctrl + V,上下文菜单等)
- 它允许您直接以文本方式获取剪贴板数据,因此您不必进行丑陋的黑客来替换HTML
虽然我不确定是否支持跨浏览器。
editor.addEventListener(paste,函数(e){
//取消粘贴
e.preventDefault();
//获取剪贴板的文本表示
var text = e.clipboardData.getData (text / plain);
//手动插入文本
document.execCommand(insertHTML,false,text);
});
I have a basic editor based on execCommand following the sample introduced here. There are three ways to paste text within the execCommand area:
- Ctrl + V
- Right Click -> Paste
- Right Click -> Paste As Plain Text
I want to allow pasting only plain text without any HTML markup. How can I force the first two actions to paste Plain Text?
Possible Solution: The way I can think of is to set listener for keyup events for (Ctrl + V) and strip HTML tags before paste.
- Is it the best solution?
- Is it bulletproof to avoid any HTML makup in paste?
- How to add listener to Right Click -> Paste?
Intercept the paste event, cancel the paste, and manually insert the text representation of the clipboard: http://jsfiddle.net/HBEzc/. This should be the most reliable:
- It catches all kinds of pasting (Ctrl+V, context menu, etc.)
- It allows you to get the clipboard data directly as text, so you don't have to do ugly hacks to replace HTML
I'm not sure of cross-browser support, though.
editor.addEventListener("paste", function(e) { // cancel paste e.preventDefault(); // get text representation of clipboard var text = e.clipboardData.getData("text/plain"); // insert text manually document.execCommand("insertHTML", false, text); });
这篇关于在execCommand中用'粘贴为纯文本'的Javascript技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!