如何在preventDefault之后创建粘贴事件?

问题描述 投票:1回答:1

我正在使用角度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();
}

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

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

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

pasteClipboardData(newData);

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

javascript html angular paste w3c
1个回答
1
投票

你不需要派遣另一个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

© www.soinside.com 2019 - 2024. All rights reserved.