gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:05:38 25 4
gpt4 key购买 nike

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

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

// Since we are canceling the paste operation, we need to manually

// paste the data into the document.

pasteClipboardData(newData);

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

最佳答案

您不需要发送另一个 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 .

关于javascript - 如何在 preventDefault 之后创建粘贴事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com