在execCommand中用'粘贴为纯文本'的Javascript技巧 [英] Javascript trick for 'paste as plain text` in execCommand

查看:1017
本文介绍了在execCommand中用'粘贴为纯文本'的Javascript技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这里介绍的示例,我有一个基于 execCommand 的基本编辑器。有三种方法可以在 execCommand 区域中粘贴文本:


  • Ctrl + V
  • 右键点击 - >粘贴

  • 右键点击 - >以纯文本格式粘贴



我想只粘贴纯文本而不使用任何HTML标记。如何强制前两个操作粘贴纯文本?



可能的解决方案:我可以考虑的方式是为keyup设置侦听器(Ctrl + V)的事件并粘贴HTML标签。


  1. 是最佳解决方案吗?

  2. 如何将侦听器添加到右键单击 - >粘贴?


解决方案

拦截粘贴事件,取消粘贴,并手动插入剪贴板的文本表示: http://jsfiddle.net/HBEzc/ 。这应该是最可靠的:


  • 它可以捕捉各种粘贴(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.

  1. Is it the best solution?
  2. Is it bulletproof to avoid any HTML makup in paste?
  3. 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技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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