我知道这对聚会来说有点晚了,但我一直在努力在浏览器中捕获粘贴事件。我仍在编写代码,但到目前为止我所拥有的是http://jsfiddle.net/JgU37/42/。
代码的要点如下:
$(document).ready(function() {
// Fake paste
var doFakePaste = false;
$(document).on('keydown', function(e) {
$('#status').html('metaKey: ' + e.metaKey +
' ctrlKey: ' + e.ctrlKey +
' which: ' + e.which);
// These browser work with the real paste event
if ($.client.browser === "Chrome")
return;
if ($.client.os === "Windows" && $.client.browser === "Safari")
return;
// Check for patse keydown event
if (!doFakePaste &&
($.client.os === "Mac" && e.which == 86 && e.metaKey) ||
($.client.os !== "Mac" && e.which == 86 && e.ctrlKey)) {
doFakePaste = true;
// got a paste
if (!$("*:focus").is("input") &&
!$("*:focus").is("textarea")) {
$('#status').html('fake paste');
// Focus the offscreen editable
$('#TribblePaste').focus();
// Opera doesn't support onPaste events so we have
// to use a timeout to get the paste
if ($.client.browser === "Opera")
{
setTimeout(function() {
doFakePaste = false;
var html = $('#TribblePaste').html();
var text = $('#TribblePaste').text();
if (text == '') text = $('#TribblePaste').val();
$('#resultA').text('[o] '+html);
$('#resultB').text('[o] '+text);
$('#TribblePaste').val('');
$('#TribblePaste').text('');
$('#TribblePaste').blur();
}, 1);
}
}
}
}).on('paste', function (e) {
// Firefox is not supported - they don't
// expose the real clipboard
if ($.client.browser === 'Firefox')
return;
$('#status').html('paste event');
// real pasteing
var html = '';
var text = '';
if (window.clipboardData) // IE
{
text = window.clipboardData.getData("Text");
}
if (e.clipboardData && e.clipboardData.getData) // Standard
{
text = e.clipboardData.getData('text/plain');
text = e.clipboardData.getData('text/html');
}
if (e.originalEvent.clipboardData &&
e.originalEvent.clipboardData.getData) // jQuery
{
text = e.originalEvent.clipboardData.getData('text/plain');
html = e.originalEvent.clipboardData.getData('text/html');
}
$('#resultA').text(html);
$('#resultB').text(text);
});
// Setup the offscreen paste capture area
$('<textarea contenteditable id="TribblePaste"></textarea>').css({
'position': 'absolute',
'top': '-100000px',
'width': '100px',
'height': '100px'
}).on('paste', function(e) {
setTimeout(function() {
doFakePaste = false;
var html = $('#TribblePaste').html();
var text = $('#TribblePaste').text();
if (text == '') text = $('#TribblePaste').val();
$('#resultA').text(html);
$('#resultB').text(text);
$('#TribblePaste').val('');
$('#TribblePaste').text('');
$('#TribblePaste').blur();
}, 1);
}).appendTo('body');
$('#data').html('os: ' + $.client.os + ' browser: ' + $.client.browser);
});