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

标签 javascript google-chrome execcommand

当我使用 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/

相关文章:

javascript - 无法使用 jQuery 的 "on click"事件监听器中包含的推送命令推送到全局范围内的数组

javascript - Chrome 开发者工具 : How to copy a JSON object as text from the Sources tab or Watch pane

使用 execCommand 的 javascript 副本

javascript - "execCommand"不适用于 AngularJS

javascript - 如何检查一个表是否有具有特定ID的jquery行

javascript - Observable 不发出新值

javascript - 在 autoresizing textarea 中输入会一直聚焦在元素的顶部

javascript - 如何使用 javascript 检查 URL 是否存在

javascript - Chrome 扩展程序保存文件对话框

javascript - 在可编辑的 iframe 中使用 execCommand() 时如何与退格键相同?