复制步骤

1.选中文本

select()只对<input><textarea>有效,所以要获取到点击的值,放到input标签或textarea标签中,再选中复制

2.执行复制命令

document.execCommand("Copy");

复制栗子

input标签实现复制

const selectInputText = (textbox, startIndex, stopIndex) => {
  if (textbox.createTextRange) {
    const range = textbox.createTextRange();
    range.collapse(true);
    range.moveStart('character', startIndex);
    range.moveEnd('character', stopIndex - startIndex);
    range.select();
  } else {
    textbox.setSelectionRange(startIndex, stopIndex);
    textbox.focus();
  }
};

const copyContent = (text) => {
  const textString = text.toString();
  let input = document.querySelector('#copy-input');
  if (!input) {
    input = document.createElement('input');
    input.id = 'copy-input';
    input.readOnly = 'readOnly';
    input.contentEditable = 'true';
    input.style.position = 'absolute';
    input.style.top = document.body.scrollTop;
    input.style.zIndex = '-1000';
    document.getElementById('app').appendChild(input);
  }

  input.value = textString;
  // ios必须先选中文字且不支持 input.select();
  selectInputText(input, 0, textString.length);

  if (document.execCommand('copy')) {
    document.execCommand('copy');
    head.bridge('showToast', '手机号已复制,可快速粘贴!');
  }
  input.blur();
};

textarea标签实现复制

function selectTextArea(textArea) {
  let range = document.createRange();
  range.selectNodeContents(textArea);
  let selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  textArea.setSelectionRange(0, textArea.value.length);
}

export function copyContent(textToCopy) {
  const textString = textToCopy.toString();

  let textArea = document.createElement('textArea');
  textArea.setAttribute('readonly', true);
  textArea.setAttribute('contenteditable', true);
  textArea.value = textString;
  textArea.style.position = 'absolute';
  textArea.style.top = document.body.scrollTop;
  textArea.style.zIndex = '-1000';
  document.getElementById('app').appendChild(textArea);

  textArea.focus();
  textArea.select();

  selectTextArea(textArea);

  if (document.execCommand('copy')) {
    document.execCommand('copy');
    head.bridge('showToast', '手机号已复制,可快速粘贴!');
  }
  document.getElementById('app').removeChild(textArea);
}

时倾
794 声望2.4k 粉丝

把梦想放在心中