我發現了一個解決方案:
在按下按鍵的處理程序創建的「預」的標籤。設置內容以複製到此標籤。在此標記上進行選擇並在處理程序中返回true。這個調用鉻的標準處理程序並複製選定的文本。
如果你需要你可以設置超時恢復以前的選擇功能。我對MooTools的implementantions:
function EnybyClipboard() {
this.saveSelection = false;
this.callback = false;
this.pastedText = false;
this.restoreSelection = function() {
if (this.saveSelection) {
window.getSelection().removeAllRanges();
for (var i = 0; i < this.saveSelection.length; i++) {
window.getSelection().addRange(this.saveSelection[i]);
}
this.saveSelection = false;
}
};
this.copyText = function (text) {
var div = $('special_copy');
if (!div) {
div = new Element('pre', {'id' : 'special_copy', 'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'});
div.injectInside(document.body);
}
div.set('text', text);
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
setTimeout(this.restoreSelection.bind(this), 100);
} else
return alert('Copy not work. :(');
};
this.getPastedText = function() {
if (!this.pastedText)
alert('Nothing to paste. :(');
return this.pastedText;
};
this.pasteText = function (callback) {
var div = $('special_paste');
if (!div) {
div = new Element('textarea', {'id' : 'special_paste', 'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'});
div.injectInside(document.body);
div.addEvent('keyup', function() {
if (this.callback) {
this.pastedText = $('special_paste').get('value');
this.callback.call(this.pastedText);
this.callback = false;
this.pastedText = false;
setTimeout(this.restoreSelection.bind(this), 100);
}
}.bind(this));
}
div.set('value', '');
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
div.focus();
this.callback = callback;
} else
return alert('Fail to paste. :(');
};
}
用法:
enyby_clip = new EnybyClipboard(); //init
enyby_clip.copyText('some_text'); // place this in CTRL+C handler and return true;
enyby_clip.pasteText(function callback(pasted_text) {
alert(pasted_text);
}); // place this in CTRL+V handler and return true;
上粘貼了textarea的創建工作,並同。
抱歉,糟糕的英語 - 不是我的母語。
出於安全原因,在這些瀏覽器中可能會禁用此功能(將剪貼板設置爲任意JavaScript字符串)。 – pts 2010-12-03 09:57:21