JS实现复制文本到剪切板

时间:2018-11-07
本文章向大家介绍JS实现复制文本到剪切板,需要的朋友可以参考一下
// 是否支持复制
export const isSupportCopy = ((!!document.queryCommandSupported) && document.queryCommandSupported('copy'));
const copyTempElement = document.createElement('textarea');
copyTempElement.setAttribute('style', 'margin:0;padding:0;width:0;height:0;position:absolute;');
document.body.appendChild(copyTempElement);
// 复制文本到剪切板
export function copyText(text) {
  let succeeded;
  try {
    copyTempElement.value = text;
    copyTempElement.select();
    succeeded = document.execCommand('copy');
  } catch (err) {
    succeeded = false;
  }
  return succeeded;
}