只有在Chrome浏览器中,
我找不到任何人遇到同样的问题,虽然有很多类似的问题,但除非确实是重复的,否则请不要将此标记为重复。
https://codepen.io/jakecr/pen/XVXvKz
document.execCommand('copy')
返回true但不会复制文本,而是清空剪贴板。我找不到任何人遇到同样的问题,虽然有很多类似的问题,但除非确实是重复的,否则请不要将此标记为重复。
- 在
selection.addRange()
之前调用selection.removeAllRanges()
。 selection.getRangeAt(0).cloneContents()
返回包含正确文本的片段- 文本区域中的文本似乎没有被选择
- 如果在
document.execCommand('copy')
之前调用textarea.select()
,则文本将出现选定状态并复制到剪贴板。我不想这样做,因为它会使文本区域获得焦点并导致页面滚动。 - 在Chrome 61和63上进行测试,MacOS操作系统
- 在Safari中工作正常
https://codepen.io/jakecr/pen/XVXvKz
var textarea = document.createElement('textarea');
textarea.textContent = 'coppied text';
document.body.appendChild(textarea);
var selection = document.getSelection();
var range = document.createRange();
range.selectNodeContents(textarea);
selection.removeAllRanges();
selection.addRange(range);
// DOESN'T WORK WITHOUT THIS
// textarea.select();
console.log(selection.getRangeAt(0).cloneContents());
console.log('copy success', document.execCommand('copy'));