代码之家  ›  专栏  ›  技术社区  ›  Arghya Saha

如何在默认设置后创建粘贴事件?

  •  1
  • Arghya Saha  · 技术社区  · 7 年前

    我正在使用angular 4,并尝试使用contenteditable

    <div contenteditable='true' id='editor' [innerHtml]='data'></div>
    

    我需要检测粘贴事件,然后处理数据以删除除粗体、斜体和para之外的所有内联css和HTMl标记,然后将其粘贴为普通文本。

    我已通过成功检测到粘贴事件

    document.getElementById('editor').addEventListener('paste', handlePaste);
    function handlePaste(e) {
      var clipboardData, pastedData;
      // Stop data actually being pasted into div
      clipboardData = e.clipboardData;
      pastedData = clipboardData.getData('text/html');
      e.stopPropagation();
      e.preventDefault();
    }
    

    我能够操纵粘贴数据,但无法启动粘贴行为。使用preventDefault和stopPropagation,我能够停止粘贴的默认行为,并且使用getData,我能够从剪贴板中提取数据。但现在我被困在这里,我无法启动粘贴事件。在文档中,我们需要创建一个自定义事件,如 粘贴剪贴板数据(newData) . 但我可以找到任何关于如何创建这样的活动的参考资料。

    //由于我们正在取消粘贴操作,因此需要手动

    //将数据粘贴到文档中。

    粘贴剪贴板数据(newData);

    https://w3c.github.io/clipboard-apis/#override-paste

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nickolay    7 年前

    你不需要再派一个 paste contenteditable .

    下面是一个使用 document.execCommand("insertHTML", ...) -查看其他问题(如 this one )要使其在IE中工作:

    window.onload = function() {
      document.addEventListener('paste', function(e){
        console.log("paste handler");
        var s = e.clipboardData.getData('text/html').replace("this", "that")
        document.execCommand("insertHTML", false, s);
        e.preventDefault();
      });
    }
    <html>
    <p>1) copy <b>this</b> text</p>
    <div contenteditable id="target">
      <p>2) paste it here: ... ('this' should be replaced by 'that')</p>
    </div>

    相关: overriding the copy event .