2017-08-29 106 views
0

我在間隔一段時間後(在我的情況下,我已經用於保存4個空格後)保存自動保存數據到剪貼板的功能。你可以建議間隔。繼續使用jQuery將textarea文本複製到剪貼板

我跟着this答覆將textarea文本複製到剪貼板,這裏使用了一個單獨的按鈕將數據複製到剪貼板,但是我想不斷保存它。

我迄今爲止嘗試:

var spaceCount = 0; 
 
$('#description').keyup(function(event) { 
 
    if (event.keyCode == 32) { 
 
    ++spaceCount; 
 
    if (spaceCount % 4 == 3) { 
 
     $(this).select(); 
 
     try { 
 
     var isCopied = document.execCommand('copy'); 
 
     console.log(isCopied); 
 
     console.log("Copied to clipboard"); 
 
     } catch (e) { 
 
     console.log("Error :Copying to clipboard"); 
 
     } 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="description" cols="50" rows="4"></textarea>

的問題是文本保持選中狀態。我怎樣才能取消選擇文本?我不想用任何元素來創建,就像我在一個答案中看到的那樣。

或者你可以建議另一個解決方案,而不使用任何插件?

+1

爲什麼不使用本地存儲?剪貼板非常不穩定。見:https://www.w3schools.com/html/html5_webstorage.asp – axlj

+0

@axlj你的意思是使用任何變量? –

+0

@shantaram_t https://developer.mozilla.org/docs/Web/API/Window/localStorage – evolutionxbox

回答

0

您可以使用document.getSelection().removeAllRanges();清除所選範圍。我還添加了一些jQuery來將光標放回textarea文本的末尾。

var spaceCount = 0; 
 
$('#description').keyup(function(event) { 
 
    if (event.keyCode == 32) { 
 
    ++spaceCount; 
 
    if (spaceCount % 4 == 3) { 
 
     $(this).select(); 
 
     try { 
 
     var isCopied = document.execCommand('copy'); 
 
     console.log(isCopied); 
 
     console.log("Copied to clipboard"); 
 

 
     // clear the selected range here 
 
     document.getSelection().removeAllRanges(); 
 
     // put the cursor back at the end of the text 
 
     var val = $(this).val(); 
 
     $(this).focus().val("").val(val); 
 

 
     } catch (e) { 
 
     console.log("Error :Copying to clipboard"); 
 
     } 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="description" cols="50" rows="4"></textarea>

+0

你的解決方案正在工作,@ axlj的評論改變了我的想法,使用'window.localStorage' –