Javascript 使用 Ctrl+v 或右键单击 -> 粘贴检测粘贴的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3211505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:41:26  来源:igfitidea点击:

Detect pasted text with Ctrl+v or right click -> paste

javascript

提问by randomwebdev

Using JavaScript how do you to detect what text the user pastes into a textarea?

使用 JavaScript 如何检测用户粘贴到 textarea 中的文本?

采纳答案by Tim Down

You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?

您可以使用 paste 事件来检测大多数浏览器中的粘贴(尽管不是 Firefox 2)。处理粘贴事件时,记录当前选择,然后设置一个简短的计时器,在粘贴完成后调用函数。这个函数然后可以比较长度并知道在哪里寻找粘贴的内容。类似于以下内容。为简洁起见,获取 textarea 选择的函数在 IE 中不起作用。请参阅此处了解:如何在文本区域中获取选择的起点和终点?

function getTextAreaSelection(textarea) {
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
        var sel = getTextAreaSelection(textarea);
        var initialLength = textarea.value.length;
        window.setTimeout(function() {
            var val = textarea.value;
            var pastedTextLength = val.length - (initialLength - sel.length);
            var end = sel.start + pastedTextLength;
            callback({
                start: sel.start,
                end: end,
                length: pastedTextLength,
                text: val.slice(sel.start, end)
            });
        }, 1);
    };
}

var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
    alert(pasteInfo.text);
    // pasteInfo also has properties for the start and end character
    // index and length of the pasted text
});

回答by Abdennour TOUMI

HTML5already provides onpastenot only <input/>, but also editable elements (<p contenteditable="true" />, ...)

HTML5onpaste不仅提供了<input/>,而且还提供了可编辑的元素 ( <p contenteditable="true" />, ...)

<input type="text" onpaste="myFunction()" value="Paste something in here">

More info here

更多信息在这里

回答by Willem Mulder

Quite an old thread, but you might now use http://willemmulder.github.com/FilteredPaste.js/instead. It will let you control what gets pasted into a textarea or contenteditable.

相当古老的线程,但您现在可以改用http://willemmulder.github.com/FilteredPaste.js/。它将让您控制粘贴到 textarea 或 contenteditable 中的内容。

回答by Calixto

Works on IE 8 - 10

适用于 IE 8 - 10

Creating custom code to enable the Paste command requires several steps.

创建自定义代码以启用粘贴命令需要几个步骤。

  1. Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.
  2. Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.
  3. Specify a data format in which to paste the selection through the getData method of the clipboardData object.
  4. invoke the method in the onpaste event to execute custom paste code.
  1. 在 onbeforepaste 事件中将事件对象 returnValue 设置为 false 以启用 Paste 快捷菜单项。
  2. 通过在 onpaste 事件处理程序中将事件对象 returnValue 设置为 false 来取消客户端的默认行为。这仅适用于为其定义了默认行为的对象,例如文本框。
  3. 通过 clipboardData 对象的 getData 方法指定粘贴选择的数据格式。
  4. 调用 onpaste 事件中的方法来执行自定义粘贴代码。

To invoke this event, do one of the following:

要调用此事件,请执行以下操作之一:

  • Right-click to display the shortcut menu and select Paste.
  • Or press CTRL+V.
  • 右键单击以显示快捷菜单并选择粘贴。
  • 或按 CTRL+V。

Examples

例子

<HEAD>
<SCRIPT>
var sNewString = "new content associated with this object";
var sSave = "";
// Selects the text that is to be cut.
function fnLoad() {
    var r = document.body.createTextRange();
    r.findText(oSource.innerText);
    r.select();
}
// Stores the text of the SPAN in a variable that is set 
// to an empty string in the variable declaration above.
function fnBeforeCut() {
    sSave = oSource.innerText;
    event.returnValue = false;
}
// Associates the variable sNewString with the text being cut.
function fnCut() {
    window.clipboardData.setData("Text", sNewString);
}
function fnBeforePaste() {
    event.returnValue = false;
}
// The second parameter set in getData causes sNewString 
// to be pasted into the text input. Passing no second
// parameter causes the SPAN text to be pasted instead.
function fnPaste() {
    event.returnValue = false;
    oTarget.value = window.clipboardData.getData("Text", sNewString);
}
</SCRIPT>
</HEAD>
<BODY onload="fnLoad()">
<SPAN ID="oSource" 
      onbeforecut="fnBeforeCut()" 
      oncut="fnCut()">Cut this Text</SPAN>
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
      onbeforepaste="fnBeforePaste()" 
      onpaste="fnPaste()">
</BODY>

Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx

完整文档:http: //msdn.microsoft.com/en-us/library/ie/ms536955(v= vs.85).aspx

回答by Salil

Following may help you

以下可能对你有帮助

  function submitenter(myfield,e)
  {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == //event code of ctrl-v)
    {
      //some code here
    }

  }

  <teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea> 

回答by Michael

I like the suggestion for the right click

我喜欢右键单击的建议

$("#message").on('keyup contextmenu input', function(event) { 
  alert("ok");
});

finded here:

在这里找到:

Source: Fire event with right mouse click and Paste

来源: 鼠标右键单击和粘贴的火灾事件