在粘贴事件上获取有关文档的粘贴内容

正如问题中所提到的,如何在文档上获取粘贴的内容。截至目前,我正在创建一个文本区域和dblclick以将焦点转移到textarea,然后在textarea的粘贴事件中我正在收集数据。 我不认为这是一个好方法。 我的代码如下

$('body').dblclick(function() { $('#textare').focus(); }); Then $('#textare').keyup(function() { alert( $(this).val() ); }); 

请建议我一个替代过程。
我正在寻找替代品

 $(document).paste(function() { // Get the pasted content }); 

我正在使用谷歌浏览器。 我不想用textarea来捕捉文字。

您可以在元素中添加onpaste事件。 所有的浏览器都支持它

  onpaste="return getPastedValue(this);"  

此解决方案仅比获取文本更进一步,它实际上允许您在粘贴到元素之前编辑粘贴的内容。

它的工作原理是使用contenteditable,onpaste事件(由所有主流浏览器支持)和变异观察者(由Chrome,Firefox和IE11 +支持)

步骤1

创建一个具有contenteditable的HTML元素

 

第2步

在您的Javascript代码中添加以下事件

 document.getElementById("target_paste_element").addEventListener("paste", pasteEventVerifierEditor.bind(window, pasteCallBack), false); 

我们需要绑定pasteCallBack,因为异步调用变异观察器。

第3步

将以下函数添加到您的代码中

 function pasteEventVerifierEditor(callback, e) { //is fired on a paste event. //pastes content into another contenteditable div, mutation observer observes this, content get pasted, dom tree is copied and can be referenced through call back. //create temp div //save the caret position. savedCaret = saveSelection(document.getElementById("target_paste_element")); var tempDiv = document.createElement("div"); tempDiv.id = "id_tempDiv_paste_editor"; //tempDiv.style.display = "none"; document.body.appendChild(tempDiv); tempDiv.contentEditable = "true"; tempDiv.focus(); //we have to wait for the change to occur. //attach a mutation observer if (window['MutationObserver']) { //this is new functionality //observer is present in firefox/chrome and IE11 // select the target node // create an observer instance tempDiv.observer = new MutationObserver(pasteMutationObserver.bind(window, callback)); // configuration of the observer: var config = { attributes: false, childList: true, characterData: true, subtree: true }; // pass in the target node, as well as the observer options tempDiv.observer.observe(tempDiv, config); } } function pasteMutationObserver(callback) { document.getElementById("id_tempDiv_paste_editor").observer.disconnect(); delete document.getElementById("id_tempDiv_paste_editor").observer; if (callback) { //return the copied dom tree to the supplied callback. //copy to avoid closures. callback.apply(document.getElementById("id_tempDiv_paste_editor").cloneNode(true)); } document.body.removeChild(document.getElementById("id_tempDiv_paste_editor")); } function pasteCallBack() { //paste the content into the element. restoreSelection(document.getElementById("target_paste_element"), savedCaret); delete savedCaret; pasteHtmlAtCaret(this.innerHTML, false, true); } saveSelection = function(containerEl) { if (containerEl == document.activeElement) { var range = window.getSelection().getRangeAt(0); var preSelectionRange = range.cloneRange(); preSelectionRange.selectNodeContents(containerEl); preSelectionRange.setEnd(range.startContainer, range.startOffset); var start = preSelectionRange.toString().length; return { start: start, end: start + range.toString().length }; } }; restoreSelection = function(containerEl, savedSel) { containerEl.focus(); var charIndex = 0, range = document.createRange(); range.setStart(containerEl, 0); range.collapse(true); var nodeStack = [containerEl], node, foundStart = false, stop = false; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { var nextCharIndex = charIndex + node.length; if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) { range.setStart(node, savedSel.start - charIndex); foundStart = true; } if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) { range.setEnd(node, savedSel.end - charIndex); stop = true; } charIndex = nextCharIndex; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } function pasteHtmlAtCaret(html, returnInNode, selectPastedContent) { //function written by Tim Down var sel, range; if (window.getSelection) { // IE9 and non-IE sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); // Range.createContextualFragment() would be useful here but is // only relatively recently standardized and is not supported in // some browsers (IE9, for one) var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } var firstNode = frag.firstChild; range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); if (returnInNode) { range.setStart(lastNode, 0); //this part is edited, set caret inside pasted node. } else { range.setStartAfter(lastNode); } if (selectPastedContent) { range.setStartBefore(firstNode); } else { range.collapse(true); } sel.removeAllRanges(); sel.addRange(range); } } } else if ( (sel = document.selection) && sel.type != "Control") { // IE < 9 var originalRange = sel.createRange(); originalRange.collapse(true); sel.createRange().pasteHTML(html); if (selectPastedContent) { range = sel.createRange(); range.setEndPoint("StartToStart", originalRange); range.select(); } } 

}

代码的作用:

  1. 有人使用ctrl-v,contextmenu或其他方法触发粘贴事件
  2. 在粘贴事件中,创建了一个具有contenteditable的新元素(具有contenteditable的元素具有提升的权限)
  3. 保存目标元素的插入符号位置。
  4. 焦点设置为新元素
  5. 内容将粘贴到新元素中并在DOM中呈现。
  6. 变异观察者捕获了这个(它记录了对dom树和内容的所有更改)。 然后激发突变事件。
  7. 粘贴内容的dom被克隆到变量中并返回到回调。 临时元素被破坏。
  8. 回调接收克隆的DOM。 插入符号已恢复。 您可以在将其附加到目标之前对其进行编辑。 元件。 在这个例子中,我使用Tim Downs函数来保存/恢复插入符并将HTML粘贴到元素中。

非常感谢Tim Down

像这样的东西:

 $(“yourTextAres”)。bind('paste',function(){

警报($(本).VAL());
 });