Javascript 在粘贴事件中获取文档上粘贴的内容

Javascript 在粘贴事件中获取文档上粘贴的内容,javascript,jquery,Javascript,Jquery,如问题中所述,如何在文档上粘贴内容。目前,我正在创建一个文本区域并单击dblclick将焦点移到文本区域,然后在文本区域的粘贴事件上收集数据。我认为这不是一个好办法。我的代码在下面 $('body').dblclick(function() { $('#textare').focus(); }); Then $('#textare').keyup(function() { alert( $(this).val() ); }); 请给我推荐一个替代流程。 我正在寻找像

如问题中所述,如何在文档上粘贴内容。目前,我正在创建一个文本区域并单击dblclick将焦点移到文本区域,然后在文本区域的粘贴事件上收集数据。我认为这不是一个好办法。我的代码在下面

$('body').dblclick(function()
{
      $('#textare').focus();
});

Then 
$('#textare').keyup(function()
{
      alert( $(this).val() );
});
请给我推荐一个替代流程。
我正在寻找像这样的替代品

$(document).paste(function()
{
    // Get the pasted content
});
我正在使用谷歌浏览器。我不想使用textarea捕捉文本。

类似这样的内容:

$("yourTextAres").bind('paste', function() { alert($(this).val()); }); $(“yourTextAres”).bind('paste',function(){ 警报($(this.val()); });
您可以将
onpaste
事件添加到元素中。所有浏览器都支持它

 onpaste="return getPastedValue(this);"


 <script type="text/javascript">
        function getPastedValue (obj) {
            alert(obj.innerHTML);
           return false;
      }
 </script>
onpaste=“return getPastedValue(this);”
函数getPastedValue(obj){
警报(obj.innerHTML);
返回false;
}

此解决方案超出了仅获取文本的范围,它实际上允许您在粘贴到元素之前编辑粘贴的内容

它通过使用contenteditable、onpaste事件(所有主要浏览器都支持)和浏览器(Chrome、Firefox和IE11+支持)工作

步骤1

使用contenteditable创建HTML元素

<div contenteditable="true" id="target_paste_element"></div>
我们需要绑定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();
    }
}
函数粘贴事件验证编辑器(回调,e)
{
//在粘贴事件时激发。
//将内容粘贴到另一个contenteditable div中,变异观察者观察到这一点,内容被粘贴,dom树被复制,并且可以通过回调被引用。
//创建临时div
//保存插入符号位置。
savedCaret=saveSelection(document.getElementById(“目标粘贴元素”);
var tempDiv=document.createElement(“div”);
tempDiv.id=“id\u tempDiv\u粘贴编辑器”;
//tempDiv.style.display=“无”;
文件.body.appendChild(tempDiv);
tempDiv.contentEditable=“true”;
tempDiv.focus();
//我们必须等待变化的发生。
//附加一个突变观察者
if(窗口['MutationObserver'])
{
//这是一个新功能
//observer出现在firefox/chrome和IE11中
//选择目标节点
//创建一个观察者实例
tempDiv.observer=newmutationobserver(粘贴MutationObserver.bind(窗口,回调));
//观察员的配置:
var config={attributes:false,childList:true,characterData:true,subtree:true};
//传入目标节点以及观察者选项
tempDiv.observer.observe(tempDiv,config);
}   
}
函数PasteOnObserver(回调)
{
document.getElementById(“id_tempDiv_粘贴编辑器”).observer.disconnect();
删除document.getElementById(“id\u tempDiv\u paste\u editor”).observer;
如果(回调)
{
//将复制的dom树返回到提供的回调。
//复制以避免关闭。
apply(document.getElementById(“id_tempDiv_paste_editor”).cloneNode(true));
}
document.body.removeChild(document.getElementById(“id\u tempDiv\u粘贴编辑器”);
}
函数pasteCallBack()
{
//将内容粘贴到元素中。
恢复选择(document.getElementById(“target\u paste\u element”),savedCaret);
删除savedCaret;
pasteHtmlAtCaret(this.innerHTML,false,true);
}   
saveSelection=函数(containerell){
if(containerell==document.activeElement)
{
var range=window.getSelection().getRangeAt(0);
var preselection range=range.cloneRange();
预选范围。选择节点内容(containerell);
预选range.setEnd(range.startContainer,range.startOffset);
var start=preSelectionRange.toString().length;
返回{
开始:开始,
结束:开始+范围.toString().length
};
}
};
restoreSelection=函数(containeerl、savedSel){
containerere.focus();
var charIndex=0,range=document.createRange();
range.setStart(containerell,0);
范围。塌陷(真);
var nodeStack=[containerell],node,foundStart=false,stop=false;
而(!stop&&(node=nodeStack.pop()){
if(node.nodeType==3){
var nextCharIndex=charIndex+node.length;

如果(!foundStart&&savedSel.start>=charIndex&&savedSel.start=charIndex&&savedSel.end此问题/答案可能会对您有所帮助?@JonathonG我似乎在使用与已接受答案相同的方法并寻找替代方法。我没有否决,但这不会告诉您粘贴了什么,它只会告诉您字段的当前值-过去e不一定会替换字段中已经存在的内容。(假设您的浏览器甚至支持“粘贴”事件,但并非所有浏览器都支持。)感谢您的回答,但我清楚地提到,我想使用当前方法的替代方法。
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();
    }
}