关于javascript:js-实现复制文本到剪贴板

5次阅读

共计 1913 个字符,预计需要花费 5 分钟才能阅读完成。

复制步骤

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);
}
正文完
 0