jQuery在页面上的任意位置检测粘贴事件,然后“重定向";它到Textarea

问题描述:

我正在寻求创建一种轻松粘贴体验",用户可以在页面上的任意位置点击ctrl-v,将其剪贴板数据粘贴到文本区域中.我希望他们能够将文本粘贴到textarea中,而不会使textarea成为焦点.

I'm looking to create an "easy paste experience", where the user can hit ctrl-v anywhere on the page to paste their clipboard data into a textarea. I want them to be able to paste text into the textarea without the textarea being focused.

我知道我可以使用以下代码来检测粘贴事件:

I know I can use this code to detect a paste event:

$('html').bind('paste', function(e) {

});

但是我不知道如何获取剪贴板数据并将其移动"到文本区域,或者甚至是否可能(访问用户剪贴板的限制).

But I don't know how to grab the clipboard data and "move" it to the textarea, or if this is even possible (what with the restrictions on accessing the user's clipboard).

在Firefox中是不可能的.在IE,Safari和Chrome中,您可以执行以下操作:

It is not possible in Firefox. In IE, Safari and Chrome you can do the following:

$('html').bind('paste', function(e) {
    e.preventDefault();
    if(e.originalEvent.clipboardData){
       var text = e.originalEvent.clipboardData.getData("text/plain");
       alert(text);
     }
});