我试图将文本复制为 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/