我有以下用于复制到剪贴板的JS代码:
function copyAll(copyEl){
var textToCopy = $(copyEl)[0];
var range = document.createRange();
range.selectNode(textToCopy);
window.getSelection().addRange(range);
try {
// Now that text is selected, execute the copy command
var copyRet = document.execCommand('copy');
var msg = copyRet ? 'successful' : 'unsuccessful';
$('#copyResult').stop(true, true).fadeOut(0).html('Copied to clipboard').fadeIn(500).fadeOut(3000);
// Remove the selections
window.getSelection().removeAllRanges();
console.log('Copy command was ' + msg);
}
catch(err) {
$('#copyResult').stop(true, true).fadeOut(0).html('Oops, unable to copy').fadeIn(500).fadeOut(3000);
console.log('Oops, unable to copy');
}
}
执行此功能时,我收到此错误并登录控制台:
Discontiguous selection is not supported.
Copy command was successful
在这一行:
window.getSelection().addRange(range);
文本未被复制。
那么,我怎么会得到一个错误,我仍然得到Copy command was successful
?
此外,始终未遵循此行为。有时,我没有收到此错误,在其他时候,我收到此错误,但文本仍然被复制到剪贴板。
我只在Chrome上工作。
答案 0 :(得分:0)
看起来这是Chrome浏览器方面的一个错误。检查它现在是否正常工作。更多详情here。
答案 1 :(得分:0)
引发此错误的原因是选择对象的rangeCount
不为零。
由于@dropout已经提到Chrome bug,如果它已经有选择范围,它将避免addRange到Selection Object。
消息'复制命令成功'由于非空选择范围而被接收。所以无论选择什么都被添加了。
要解决此问题,您应该检查rangeCount。如果rangeCount不为0,则可以触发window.getSelection().empty()
或window.getSelection().removeAllRanges()
,然后仅触发addRange
并转到copy
命令。
function copyAll(copyEl){
var textToCopy = $(copyEl)[0];
var range = document.createRange();
if(range.rangeCount > 0){
range.removeAllRanges();
}
range.selectNode(textToCopy);
window.getSelection().addRange(range);
try {
// Now that text is selected, execute the copy command
var copyRet = document.execCommand('copy');
var msg = copyRet ? 'successful' : 'unsuccessful';
$('#copyResult').stop(true, true).fadeOut(0).html('Copied to clipboard').fadeIn(500).fadeOut(3000);
// Remove the selections
window.getSelection().removeAllRanges();
console.log('Copy command was ' + msg);
}
catch(err) {
$('#copyResult').stop(true, true).fadeOut(0).html('Oops, unable to copy').fadeIn(500).fadeOut(3000);
console.log('Oops, unable to copy');
}
}