继续使用jQuery将textarea文本复制到剪贴板

时间:2017-08-29 12:52:34

标签: javascript jquery html clipboard

我在一段时间后实现了将数据自动保存到剪贴板的功能(在我的情况下,我习惯在4个空格后保存)。你可以建议间隔。

我已按照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>
&#13;
&#13;
&#13;

问题是文本保持选中状态。如何取消选择文字?我不想像我在一个答案中看到的那样使用任何元素。

或者你可以在不使用任何插件的情况下推荐另一种解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以使用document.getSelection().removeAllRanges();清除所选范围。我还添加了一些jQuery来将光标放回textarea中文本的末尾。

&#13;
&#13;
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");
      }
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="description" cols="50" rows="4"></textarea>
&#13;
&#13;
&#13;

相关问题