簡體   English   中英

繼續使用jQuery將textarea文本復制到剪貼板

[英]Continue copying textarea text to clipboard using jQuery

我正在一段時間后實現將數據自動保存到剪貼板的功能(在我的情況下,我曾經習慣於在4個空格后保存)。 您可以建議間隔。

我已經按照這個答案將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> 

問題是文本仍處於選中狀態。 如何取消選擇文本? 我不想使用在一個答案中看到的任何要創建的元素。

還是您可以建議不使用任何插件的其他解決方案?

您可以使用document.getSelection().removeAllRanges();清除所選范圍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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM