如何恢复选择?

时间:2016-04-29 18:03:29

标签: javascript

我正在使用此代码将一些文本从<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。

澄清:我想复制所有文本(就像这个功能一样)但不改变他们现有的选择。

1 个答案:

答案 0 :(得分:2)

我现在明白了。这至少应该适用于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/