How can I handle the paste selected through right click in javascript? I tried with "onpaste" event and all other html events available but nothing works.
问题:
回答1:
The onpaste event should work in all modern browsers (UPD Including Opera >= 12.101).
Bind it in jQuery like this:
Here's a live example: http://jsfiddle.net/7N6Xq/
In pure JavaScript it would look something like this for modern browsers
elem.addEventListener ("paste", handler, false); // all browsers and IE9+
and for old IE versions:
elem.attachEvent ("onpaste", handler); // IE<9
You can also combine it with oninput and other events (change, propertychange, dragdrop, etc.) to create a relatively bulletproof tracking of content change.
Footnotes:
1 Opera supports Clipboard API starting from Presto/2.10.286 which corresponds to 12.10 as suggested here. Blink versions of Opera (starting from 15) should also support it but I am unable to test it as there is still no Linux version.
回答2:
The event isn't exposed by default as "onpaste" IIRC. You can do it quite simply in jQuery by issuing
jQuery(document).bind('paste', function(e){ alert('paste event caught') });
回答3:
I was surprised question #4532473 got closed unanswered about what happens if you want to capture the afterpaste event. As this is probably the problem half of the cases a possible approach in firefox (tested) is to register an oninput event right inside the onpaste handler and remove the oninput handler as soon as it's done executing.
In ie the onpropertychange should be used instead of oninput. (not tested)
回答4:
Nice pure JS solution (as requested...) is available on the Mozilla dev site
<!DOCTYPE html> <html> <head> <title>onpaste event example</title> </head> <body> <h1>Play with this editor!</h1> <textarea id="editor" rows="3" cols="80"> Try pasting text into this area! </textarea> <script> function log(txt) { document.getElementById("log").appendChild(document.createTextNode(txt + "\n")); } function pasteIntercept(evt) { log("Pasting!"); } document.getElementById("editor").addEventListener("paste", pasteIntercept, false); </script> <h2>Log</h2> <textarea rows="15" cols="80" id="log" readonly="true"></textarea> </body> </html>