javascript - document.execCommand ('copy' ) 不起作用,即使创建了 DOM 元素

标签 javascript

我试图将文本复制为 onClick 事件,但它似乎没有获取该值。这是我所拥有的:

  const copyText = () => {
    const input = document.createElement("input");
    input.innerHTML = 'test text';
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    console.log("input", input);
  };

  copyText();

我做错了什么?

最佳答案

要回答您的问题“我做错了什么?”,您可能应该使用 input.value 而不是 input.innerHTML。然而,让“复制到剪贴板”在所有平台上运行是一场噩梦。经过大量的研究和实验,我最终得出:

// Adapted from https://gist.githubusercontent.com/Chalarangelo/4ff1e8c0ec03d9294628efbae49216db/raw/cbd2d8877d4c5f2678ae1e6bb7cb903205e5eacc/copyToClipboard.js.
export function copyToClipboard(text: string): boolean {
    // Create and append textarea to body:
    const textarea = document.createElement('textarea');
    textarea.setAttribute('readonly', 'true'); // Method needed because of missing TypeScript definition.
    textarea.contentEditable = 'true';
    textarea.style.position = 'absolute';
    textarea.style.top = '-1000px';
    textarea.value = text;
    document.body.appendChild(textarea);

    // Save the current selection of the user:
    const selectedRange = document.getSelection()!.rangeCount > 0 ? document.getSelection()!.getRangeAt(0) : false;

    // Select the content of the textarea:
    textarea.select(); // Ordinary browsers
    textarea.setSelectionRange(0, textarea.value.length); // iOS

    // Try to copy the range to the clipboard:
    let success: boolean;
    try {
        success = document.execCommand('copy');
    } catch (error) {
        console.error('Could not copy to the clipboard.', error);
        alert('Could not copy to the clipboard.');
        success = false;
    }

    // Remove the added textarea again:
    document.body.removeChild(textarea);

    // Restore the selection of the user:
    if (selectedRange) {
        document.getSelection()!.removeAllRanges();
        document.getSelection()!.addRange(selectedRange);
    }

    return success;
}

请注意,这是用 TypeScript 编写的。对于 JavaScript,只需删除所有 : string: boolean!

关于javascript - document.execCommand ('copy' ) 不起作用,即使创建了 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60317969/

相关文章:

JavaScript 不输出左尖括号

javascript - 全局词典/范围问题

javascript - 滑动整个 jQuery slider 范围

javascript - html iframe vs jquery.load() 动态添加内容时(无 php 等)

javascript - CSS Span 标签导致换行 - 使用网格布局时

javascript - 如何使用 momentJS 比较两个日期而忽略年份值?

javascript - 使用 Jquery 隐藏一些文本

javascript - 有没有快速的方法来替换 IE 中的大 tbody?

javascript - Discord Js - 不同的线路

javascript - 如何解析从 Datatables ajax 调用接收到的 JSON?