此解决方案仅适用于会调用所需操作的击键。它的工作原理是在用户完成相关击键之前将用户的光标移动到 textarea 元素中。它仅适用于文本输入。我已经在 Firefox 和 chrome 中工作了。IE 可以使用 clipboardData 对象(这比这个 hack 更可取)。
在您的 html 某处,您应该创建一个 textarea 元素,该元素具有任意大的行和 cols 属性。“剪贴板文本区域”元素将是粘贴和复制数据的保存区域。我使用一些样式属性隐藏元素。
剧本:
var desiredClipboardContents = 'It works';
function onCopyKeyPressed() {
// The trick here is to populate the textarea with
// the text you want copied before the user releases
// the copy keystroke.
var textarea = document.getElementById('clipboard-textarea');
textarea.value = desiredClipboardContents;
textarea.focus();
textarea.select();
}
function onPasteKeyPressed() {
var textarea = document.getElementById('clipboard-textarea');
textarea.value = '';
textarea.focus();
// The trick here is to delay slurping the content
// that arrives in the textarea element until after
// the paste keystroke is completed. The 750 ms timeout
// provides the necessary delay.
setTimeout("finishedPasting", 750);
}
function finishedPasting() {
var textarea = document.getElementById('clipboard-textarea');
alert("Received from clipboard-paste: " + textarea.value);
}