仅在 Chrome 上 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'));
最佳答案
我不太清楚这里到底发生了什么……
似乎在 value
和文本区域的 textContent
属性之间应该使用什么不匹配。
Chrome 似乎总是使用 value
,而 Firefox 使用 textContent
。
btn.onclick = e => {
const txt = document.createElement('textarea');
document.body.appendChild(txt);
txt.value = 'from value'; // chrome uses this
txt.textContent = 'from textContent'; // FF uses this
var sel = getSelection();
var range = document.createRange();
range.selectNode(txt);
sel.removeAllRanges();
sel.addRange(range);
if(document.execCommand('copy')){
console.log('copied');
}
document.body.removeChild(txt);
}
<button id="btn">Copy!</button>
<textarea>You can paste here
</textarea>
由于 chrome 不查看 textContent
属性, Range#selectNodeContents 将在此浏览器上不选择任何内容...
但是,您可以使用 Range#selectNode 在这种情况下应该返回相同的结果,并将解决该问题。
document.getElementById('btn').addEventListener('click', function(){
var textarea = document.createElement('textarea');
textarea.textContent = 'copied text';
document.body.appendChild(textarea);
var selection = document.getSelection();
var range = document.createRange();
// range.selectNodeContents(textarea);
range.selectNode(textarea);
selection.removeAllRanges();
selection.addRange(range);
console.log('copy success', document.execCommand('copy'));
selection.removeAllRanges();
document.body.removeChild(textarea);
})
<button id="btn">copy</button>
<textarea>You can paste here</textarea>
关于javascript - document.execCommand ('copy' ) 在 Chrome 上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879184/