如何恢复所选内容

How to restore selection?

本文关键字:恢复 何恢复      更新时间:2023-09-26

我正在使用此代码将一些文本从<textarea>复制到剪贴板:

function copy() {
    var txtInput = document.getElementById('txtInput');
    txtInput.select();
    var success;
    try {
        success = document.execCommand('copy');
    } catch(err) {
        success = false;
    }
    if(!success) {
        alert('Copy failed');
    }
}

但是,我不想打乱用户的选择。我怎样才能把它恢复到以前的样子?

我只需要支持Safari的最新版本。

澄清:我想复制所有文本(就像此功能一样),但不更改其现有选择。

我现在明白了。这应该至少在Chrome 50+中有效。它将允许您突出显示文本、复制文本、保持突出显示并确保其在剪贴板上。

function getSelectionText() {
  var txtInput = document.getElementById('txtInput');
  if (txtInput.selectionStart != txtInput.selectionEnd) { // check the user has selected some text inside field
    //get actual text
    var selectedtext = txtInput.value.substring(txtInput.selectionStart, txtInput.selectionEnd);
    //set original highlight
    txtInput.setSelectionRange(txtInput.selectionStart, txtInput.selectionEnd)
    return selectedtext;
  }
}
function copy() {
  //check our log to be sure
  console.log(getSelectionText());
  try {
    window.document.execCommand('copy');
  } catch (err) {
    alert('Copy failed');
  }
}

试试看:

https://jsfiddle.net/kwscmech/4/

这里有一个参考:http://www.javascriptkit.com/javatutors/copytoclipboard.shtml

更新:根据评论

function getSelectionText(cb) {
  var txtInput = document.getElementById('txtInput');
  if (txtInput.selectionStart != txtInput.selectionEnd) { // check the user has selected some text inside field
    //get selected text
    var selectedtext = txtInput.value.substring(txtInput.selectionStart, txtInput.selectionEnd);
    var partial = {
      start: txtInput.selectionStart,
      end: txtInput.selectionEnd
    };
    //get all text
    var allText = txtInput.select();
    cb();
    //set original highlight
    txtInput.setSelectionRange(partial.start, partial.end);
  }
}
function copy() {
    console.log('copying')
  getSelectionText(function() {
    //check our log to be sure
    console.log('callback');
    try {
      window.document.execCommand('copy');
    } catch (err) {
      alert('Copy failed');
    }
  })
}

https://jsfiddle.net/kwscmech/5/