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

时间:2010-07-09 09:49:08

标签: javascript

如何使用JS检测用户在textarea中粘贴的文本?

8 个答案:

答案 0 :(得分:18)

您可以使用粘贴事件来检测大多数浏览器中的粘贴(特别是Firefox 2)。处理粘贴事件时,记录当前选择,然后设置一个在粘贴完成后调用函数的简短计时器。然后,此函数可以比较长度并知道在哪里查找粘贴的内容。像下面这样的东西。为简洁起见,获取textarea选择的函数在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 :(得分:9)

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

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

More info here

答案 2 :(得分:4)

相当旧的帖子,但您现在可能会使用http://willemmulder.github.com/FilteredPaste.js/。它可以让你控制粘贴到textarea或contenteditable的内容。

答案 3 :(得分:2)

适用于IE 8 - 10

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

  1. 在onbeforepaste事件中将事件对象returnValue设置为false以启用“粘贴”快捷菜单项。
  2. 通过在onpaste事件处理程序中将事件对象returnValue设置为false来取消客户端的默认行为。这仅适用于具有为其定义的默认行为的对象,例如文本框。
  3. 指定通过clipboardData对象的getData方法粘贴选择的数据格式。
  4. 调用onpaste事件中的方法来执行自定义粘贴代码。
  5. 要调用此事件,请执行以下操作之一:

    • 右键单击以显示快捷菜单,然后选择粘贴。
    • 或按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

答案 4 :(得分:1)

以下可能对您有所帮助

  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> 

答案 5 :(得分:1)

我喜欢右键点击的建议

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

在这里找到:

来源: Fire event with right mouse click and Paste

答案 6 :(得分:0)

您可以使用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>

答案 7 :(得分:0)

当 、 或 元素的值已更改时,将触发输入事件。

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


})