jQuery Detect Paste Event Anywhere on Page and “Redirect” it to Textarea

岁酱吖の 提交于 2019-12-12 09:02:02

问题


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


回答1:


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



回答2:


It is not possible to access the copy buffer from JavaScript (or Flash, though there is a Flash project called ZeroClipboard that can add text to the copy buffer it cannot read it back).




回答3:


It is possible to do what you are trying in firefox, capture Ctrl-V and redirect it to a textarea / text input.

However you can't do it by listening to the onpaste event in firefox due to security as the other poster said, but it is possible by listening to the keydown event and capturing Ctrl+V.

In all browsers, in general you can't access the clipboard directly (it's possible to set using flash, or I think in some versions of Internet Explorer it may have been possible).

You can listen for the keydown event on the window and check if Ctrl+V is pressed.

Then you can focus the input / textarea, don't cancel propagation of the event, and firefox will happily stick the text where you want it to go.

You can then listen to the onpaste or onchange event of the input to process the text further.

HTML:

<textarea id='redirect_ta'></textarea>

JS:

$(window).keydown(function(event) {
    if(event.ctrlKey && event.keyCode == 0x56) {
        $('#redirect_ta').focus();
    }
});

Here is a JSFiddle illustrating this:

http://jsfiddle.net/DK536/2/

Works on Firefox, Chrome and Internet Explorer.



来源:https://stackoverflow.com/questions/14131617/jquery-detect-paste-event-anywhere-on-page-and-redirect-it-to-textarea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!