chrome使用execCommand('copy')添加回车

chrome adds carriage returns using execCommand('copy')

本文关键字:添加 回车 copy 使用 execCommand chrome      更新时间:2023-09-26

当我使用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');