美文网首页
js实现复制功能

js实现复制功能

作者: MISS_3ca2 | 来源:发表于2025-04-24 14:41 被阅读0次
import throttle from "lodash/throttle";
const copyToClipboard = throttle(async (text: string) => {
    let isCopied = false;
    // 兼容
    if (!navigator.clipboard) {
      isCopied = fallbackCopyTextToClipboard(text);
    } else {
      try {
        await navigator.clipboard.writeText(text);
        isCopied = true;
        errorMessage.value = "";
      } catch (error) {
        errorMessage.value = "copy fail: " + error;
        isCopied = false;

        show("T_Toast_Copy_Error", {
          type: "none",
          duration: 1500,
        });
      }
    }

    if (isCopied) {
      alert("T_Toast_Copy_Success);
    }
    return isCopied;
  }, 500);

  const fallbackCopyTextToClipboard = (text: string) => {
    let isCopied = false;
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed"; // 避免页面在移动的时候变动
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
      document.execCommand("copy");
      isCopied = true;
      errorMessage.value = "";
      console.log("Backup: Text copied to clipboard");
    } catch (error) {
      errorMessage.value = "Backup: Unable to copy";
      isCopied = false;
      console.error("Backup: Oops, unable to copy", error);
      alert("T_Toast_Copy_Error");
    }
    document.body.removeChild(textArea);
    return isCopied;
  };

相关文章

网友评论

      本文标题:js实现复制功能

      本文链接:https://www.haomeiwen.com/subject/smknbjtx.html