我在我的网站上添加了一个鼠标右键contextMenu,其中包含功能(剪切,复制,粘贴)。我使用了document.executeCommand()。剪切和复制可以工作。但是粘贴没有工作在chrome(它在IE中工作)。我该如何解决这个问题。
答案 0 :(得分:2)
是的,这不起作用。但一切都不会丢失。您可以从粘贴事件中捕获剪贴板的内容。
我在这里写到: http://blog.dmbcllc.com/cross-browser-javascript-copy-and-paste/
这里有一个github: https://github.com/DaveMBush/CrossBrowserCopyAndPaste
这是适用于IE,FF和Chrome的所有直接javascript(我已经测试过)
(function () {
var systemPasteReady = false;
var systemPasteContent;
function copy(target) {
// standard way of copying
var textArea = document.createElement('textarea');
textArea.setAttribute('style','width:1px;border:0;opacity:0;');
document.body.appendChild(textArea);
textArea.value = target.innerHTML;
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
var textArea;
function paste(target) {
if (window.clipboardData) {
target.innerText = window.clipboardData.getData('Text');
return;
}
function waitForPaste() {
if (!systemPasteReady) {
setTimeout(waitForPaste, 250);
return;
}
target.innerHTML = systemPasteContent;
systemPasteReady = false;
document.body.removeChild(textArea);
textArea = null;
}
// FireFox requires at least one editable
// element on the screen for the paste event to fire
textArea = document.createElement('textarea');
textArea.setAttribute('style', 'width:1px;border:0;opacity:0;');
document.body.appendChild(textArea);
textArea.select();
waitForPaste();
}
function systemPasteListener(evt) {
systemPasteContent = evt.clipboardData.getData('text/plain');
systemPasteReady = true;
evt.preventDefault();
}
function keyBoardListener(evt) {
if (evt.ctrlKey) {
switch(evt.keyCode) {
case 67: // c
copy(evt.target);
break;
case 86: // v
paste(evt.target);
break;
}
}
}
window.addEventListener('paste',systemPasteListener);
document.getElementById('element1').addEventListener('keydown', keyBoardListener);
document.getElementById('element2').addEventListener('keydown', keyBoardListener);
})();