【问题标题】:Detect pasted text with Ctrl+v or right click -> paste使用 Ctrl+v 或右键单击检测粘贴的文本 -> 粘贴
【发布时间】:2010-07-09 09:49:08
【问题描述】:

使用 JavaScript 如何检测用户粘贴到文本区域的文本?

【问题讨论】:

  • 不行,例如我粘贴“test textarea”,我想检测粘贴的是什么文本,在这种情况下-“test textarea”
  • 你可能无法跨浏览器...
  • 我想知道粘贴文本的长度。

标签: javascript


【解决方案1】:

您可以在大多数浏览器中使用 paste 事件来检测粘贴(但尤其是 Firefox 2 除外)。当您处理粘贴事件时,记录当前选择,然后设置一个简短的计时器,在粘贴完成后调用一个函数。然后,此功能可以比较长度并知道在哪里查找粘贴的内容。类似于以下内容。为简洁起见,获取文本区域选择的功能在 IE 中不起作用。请参阅此处了解相关内容:How to get the start and end points of selection in text area?

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

【讨论】:

  • 是否每 1 毫秒轮询一次?
  • @chug2k:不,它只在每次粘贴后 1 毫秒(或浏览器实现的任何东西)后运行该函数一次。
  • 只是为其他好奇的人提供一些附加信息- setTimeout() 的原因是 onpaste 事件发生在输入/文本区域更新之前。 (我认为该事件旨在让其他应用程序决定如何处理粘贴,例如,如果用户粘贴文件或图像等)。因此,如果您尝试在 onpaste 处理程序中读取 input/textarea 的值,它仍然包含旧文本。
【解决方案2】:

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

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

More info here

【讨论】:

【解决方案3】:

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

【讨论】:

  • 链接关闭。这比onpaste好吗?
  • @qräbnö 更新了链接;谢谢。虽然这是一个非常古老的项目,所以你必须自己弄清楚它是否仍然比简单的 onpaste 更有用......对不起!
  • 我喜欢。我可能会使用它。谢谢。
【解决方案4】:

适用于 IE 8 - 10

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

  1. 在 onbeforepaste 事件中将事件对象 returnValue 设置为 false 以启用粘贴快捷菜单项。
  2. 通过在 onpaste 事件处理程序中将事件对象 returnValue 设置为 false 来取消客户端的默认行为。这仅适用于为其定义了默认行为的对象,例如文本框。
  3. 通过 clipboardData 对象的 getData 方法指定粘贴所选内容的数据格式。
  4. 在 onpaste 事件中调用方法来执行自定义粘贴代码。

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

  • 右击显示快捷菜单并选择粘贴。
  • 或按 CTRL+V。

示例

<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>

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

【讨论】:

    【解决方案5】:

    我喜欢右击的建议

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

    在这里找到:

    来源: Fire event with right mouse click and Paste

    【讨论】:

      【解决方案6】:

      以下内容可能对您有所帮助

        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> 
      

      【讨论】:

      • 是的,但是如果我想检测用户粘贴的文本,“这里的一些代码”会是什么?
      【解决方案7】:

      当 、 或 元素的值发生变化时,输入事件会触发。

      const element = document.getElementById("input_element_id");
      element.addEventListener('input', e => {
      // insertText or insertFromPaste
         if(inputType === "insertFromPaste"){
             console.log("This text is copied");
         }
         if(inputType === "insertText"){
             console.log("This text is typed");
         }
      
      
      })
      

      【讨论】:

        【解决方案8】:

        您可以使用 html5 oninput 属性或 jquery input 事件

        <!DOCTYPE html>
        <html>
        <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script>
          $("body").on('input','#myinp',function(){
         $("span").css("display", "inline").fadeOut(2000);
          });
        </script>
        <style>
        span {
          display: none;
        }
        </style>
        </head>
        <body>
        
        <input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">
        
        <span>Nice to meet you!</span>
        
        </body>
        </html>

        【讨论】:

          猜你喜欢
          • 2013-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-17
          • 1970-01-01
          • 1970-01-01
          • 2011-07-27
          • 2020-11-30
          相关资源
          最近更新 更多