实现功能:用户点击一个按钮,系统自动复制一段文本到系统剪贴板
方案:
1.把待复制文本放入或类型的元素 A 中;
2.创建一个range对象并挂载 A 元素;
3.取窗口当前选中元素并清除,然后设置选中元素为第4步创建的range对象;
4.执行document.execCommand('copy')
let textarea = document.createElement('textarea');
textarea.id = "copyTextarea";
textarea.style.width = 0;
textarea.style.height = 0;
document.body.appendChild(textarea);
textarea = document.getElementById('copyTextarea');
textarea.innerHTML = text;
if(机型 == "ios"){
const range = document.createRange();
range.selectNode(document.getElementById('copyTextarea'));
const selection = window.getSelection();
if (selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
}else{
textarea.select(); // 选中文本(select()方法对IOS部分版本无效)
}
document.execCommand('copy');
document.body.removeChild(textarea);
---文本复制成功---
注意:通过执行el.select()也能使其获得焦点,但该方法在 Mac 下 Chrome 中有效,在 iOS 下无效(iOS某些系统版本有效)。