当我使用 document.execCommand('copy') 时,chrome 会在复制文本的末尾添加一个回车符(实际上不在 HTLM 中,而 IE 则不会(正确的行为)。 我做错了什么吗?
function copycode(){
var length=this.id.length;
var preid = this.id.substring(0,length-1);
var textnode=document.getElementById(preid);
textnode.setAttribute('contenteditable', 'true');
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(textnode);
window.getSelection().addRange(range);
var succeed;
try {
succeed = document.execCommand("copy");
}
catch(e) {
succeed = false;
}
textnode.setAttribute('contenteditable', 'false');
}
最佳答案
问题不在于执行复制命令“document.execCommand('copy')”,这工作正常。范围选择是个问题。
我遇到了同样的问题,我通过使用element.SELECT()解决了它。例如:
创建一个文本区域并将其放置在屏幕之外(隐藏不起作用)。设置值并选择完整的文本区域。
var textarea = document.createElement( "textarea" );
textarea.style.height = "0px";
textarea.style.left = "-100px";
textarea.style.opacity = "0";
textarea.style.position = "fixed";
textarea.style.top = "-100px";
textarea.style.width = "0px";
document.body.appendChild( textarea );
textarea.value = textnode.innerHTML;
textarea.select();
document.execCommand('copy');
关于javascript - chrome 使用 execCommand 添加回车符 ('copy' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259850/