实现复制代码功能

76 阅读1分钟

1.只复制了代码内容,而没有复制代码格式

function copyText(value) {
 return new Promise((res, rej) => {
  let clipboard = navigator.clipboard || {
       writeText: (text) => {
         let copyInput = document.createElement("input");
         copyInput.value = text;
         document.body.appendChild(copyInput);
         copyInput.select();
         document.execCommand("copy");
         document.body.removeChild(copyInput);
       },
     };
    clipboard?.writeText(value);
    res("成功");
  });
 }

2.复制代码内容和格式(指换行空格等)

function copyText(value) {
  return new Promise((res, rej) => {
    // 使用现代浏览器提供的 clipboard API
    if (navigator.clipboard) {
      navigator.clipboard
        .writeText(value)
        .then(() => res("成功"))
        .catch((err) => rej("失败:" + err));
    } else {
      // 兼容不支持 clipboard API 的浏览器
      let copyTextarea = document.createElement("textarea");
      copyTextarea.value = value;
      document.body.appendChild(copyTextarea);
      copyTextarea.select();
      document.execCommand("copy");
      document.body.removeChild(copyTextarea);
      res("成功");
    }
  });
}