粘贴事件不会通过paste-execCommand触发

时间:2017-04-28 07:00:57

标签: javascript html copy-paste

要求: 我想从Rich Text(DOM)中提取纯文本内容(带空格/换行格式)。

解决方案我尝试过: 模拟复制事件以获取文本& html到clipboardData。所以我可以简单地从clipboardData中获取纯文本,而不是自己处理html。

我面临的问题: 我能够通过复制事件将纯文本数据输入到clipboardData,但由于无法提取,因此不会调用粘贴事件处理程序



doCopy.addEventListener('click', function() {
  copy('demo');
});

function copy(element_id) {
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.oncopy = function() {
    debugger;
  }
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  extractPlainText();
  document.body.removeChild(aux);
}

function extractPlainText() {
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  document.body.appendChild(aux);
  aux.onpaste = function() { //Want plain text from DOM+
    debugger;
    var dataTransfer = event.clipboardData,
      data = {};
    for (var i = 0; i < dataTransfer.types.length; i++) {
      var contentType = dataTransfer.types[i];
      data[contentType] = dataTransfer.getData(contentType);
    }
  };
  aux.focus();
  document.execCommand("paste");
  document.body.removeChild(aux);
}
&#13;
#target {
  width: 400px;
  height: 100px;
  border: 1px solid #ccc;
  overflow: auto;
}

#demo {
  width: 100%;
  height: 200px;
  overflow: auto;
  border: 1px solid green;
}
&#13;
<p id="demo" contentEditable="true"><b>Bold text</b> and <u>underlined text</u>.</p>
<button id="doCopy">Copy Keeping Format</button>

<div id="target" contentEditable="true"></div>
&#13;
&#13;
&#13;

JSFiddle链接:https://jsfiddle.net/kommugopi/xjcadvyp/8/

0 个答案:

没有答案