在preventDefault之后如何创建粘贴事件? [英] How to create a paste event after preventDefault?

查看:100
本文介绍了在preventDefault之后如何创建粘贴事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using angular 4 and trying to work with on contenteditable

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

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

I need to detect paste event and then manipulate the data to remove all the inline css and HTMl tag other than bold, italics, and para and then paste it as normal text.

我已成功检测到粘贴事件,

I have successfully detected the paste event by

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();
}

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

I'm able to manipulate the pastedData but not able to initiate the paste behaviour. Using preventDefault and stopPropagation I'm able to stop the default behaviour of paste, and also using getData I'm able to extract the data from clipboard. But now I'm stuck here, I'm not able to initiate paste event. In the docs it is said that we need to create a custom event like pasteClipboardData(newData). But I could find any reference on how to create such event.

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

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

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

// paste the data into the document.

pasteClipboardData(newData);

pasteClipboardData(newData);

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

推荐答案

您不需要调度另一个 paste 事件.只需将所需的内容插入 contenteditable .

You don't need to dispatch another paste event. Just insert the content you want into the contenteditable.

以下是使用 document.execCommand("insertHTML",...)的示例-查看其他问题(例如

Here's an example using document.execCommand("insertHTML", ...) - see other questions (like this one) to make it work in 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>

相关:覆盖 copy 事件.

这篇关于在preventDefault之后如何创建粘贴事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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