前端怎么将指定的字符串,复制到剪贴板?

如题
点击复制按钮,将一个后端返回的字符串复制到剪贴板。

阅读 6.9k
4 个回答

点击按钮,js复制某内容

function copy(value, onError, onSuccess) {
  if (value === undefined) return;
  const input = document.createElement("input");
  // 设置 display为none会导致无法复制
  // input.style.display = "none";
  // 所以只能用其他方法隐藏
  input.style.opacity = 0;
  // 为了不影响布局
  input.style.position = 'fixed';
  input.style.left = "-100%";
  input.style.top = "-100%";
  input.value = value;
  document.body.appendChild(input);
  input.select()
  const success = document.execCommand("copy");
  document.body.removeChild(input);
  if (!success) {
      onError && onError();
      return;
  }
  onSuccess && onSuccess();
}

// usage
copy("target string")
// 现在试试在别处粘贴一下

监听剪切板copy事件

document.addEventListener("copy", function() {
    if (event.clipboardData || event.originalEvent) {
        const clipboardData = event.clipboardData || event.originalEvent.clipboardData;
        const value = "target string content";
        clipboardData.setData('text/plain', value);
        event.preventDefault();
    }
});

监听剪切板paste事件:

document.addEventListener("paste", function () {
    if (event.clipboardData || event.originalEvent) {
        const clipboardData = event.clipboardData || window.clipboardData;
        const value = clipboardData.getData('text');
        console.log(value);
        // TODO: do something with value
        event.preventDefault();
    }
});
只复制文本,不保留样式
$('#copyText').on('click', function (e) {
    const input = document.createElement('input');
    document.body.appendChild(input);
    input.setAttribute('value', "复制的内容")
    input.select();
    if (document.execCommand('copy')) {
        console.log(document.execCommand('copy'));
    }
    document.body.removeChild(input);
});
复制文本,同时保留样式

如果需要保留样式,需要用到textarea

$('#copy').on('click', function (e) {
   const input = document.createElement('textarea');
   document.body.appendChild(input);
   input.value = $("#textarea").innerText;
   input.select();
   if (document.execCommand('copy')) {
      console.log(document.execCommand('copy'));
   }
   document.body.removeChild(input);
});

可以参考这个网站 https://www.nalani521.cn/index.php/2021/03/16/js%E5%A4%8D%E5%88%B6%E6%96%87%E6%9C%AC/

新手上路,请多包涵
export function copyResult(str: string) {
  const oInput = document.createElement('input')
  oInput.value = str
  document.body.appendChild(oInput)
  oInput.select()
  const successful = document.execCommand('copy')
  oInput.remove()
  return successful
}
navigator.clipboard.writeText(str) // 网站需启用https
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题