2017-08-29 107 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' –