2016-06-14 22 views
0

我有複製到剪貼板下面的JS代碼: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

看起來這是Chrome的一面。檢查它現在是否正常工作。更多詳情here

0

導致此錯誤的原因是因爲選擇對象的rangeCount不爲零。

由於@dropout提到了Chrome bug,如果它已經有選擇範圍,它將避免選擇對象的addRange。

由於非空選擇範圍,因此收到'複製命令成功'消息。所以無論選擇什麼都被添加了。

要解決這個問題,你應該檢查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'); 
    } 

}