Javascript document.execCommand('copy')不工作,即使创建了DOM元素
我试图将文本复制为onClick事件,但它似乎没有获取值。以下是我所拥有的: 常量copyText==>{ 常量输入=document.createElementinput; input.innerHTML='测试文本'; document.body.appendChildinput; 输入。选择; 文件副本; document.body.removeChildinput; console.loginput,输入; };Javascript document.execCommand('copy')不工作,即使创建了DOM元素,javascript,Javascript,我试图将文本复制为onClick事件,但它似乎没有获取值。以下是我所拥有的: 常量copyText==>{ 常量输入=document.createElementinput; input.innerHTML='测试文本'; document.body.appendChildinput; 输入。选择; 文件副本; document.body.removeChildinput; console.loginput,输入; }; 文案 要回答您的问题“我做错了什么?”,您可能应该使用input.val
文案 要回答您的问题“我做错了什么?”,您可能应该使用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,只需删除all:string、:boolean和 我的回答解决了你的问题吗?如果没有,你可以找到很多灵感。