美文网首页
前端学习笔记--js实现复制功能

前端学习笔记--js实现复制功能

作者: 沧澈 | 来源:发表于2018-10-20 20:41 被阅读0次

    js实现点击按钮,复制文字内容

    • 核心原理
      利用浏览器提供的copy命令,实现复制功能
    document.execCommand("copy");
    
    • 如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,复制文本。
      注意: select() 方法只对 <input> 和 <textarea> 有效
    var obj= document.getElementById("demo");
    obj.select(); 
    document.execCommand("copy");
    
    • 非输入框情况下,先创建一个临时的input,将input的value设置为想要复制的文本内容,执行浏览器复制功能后,再将input删除。
    function copy(value){
        var input = document.createElement('input');
        input.setAttribute('readonly', 'readonly');
        input.setAttribute('value', value);
        document.body.appendChild(input);
        input.select();
        if (document.execCommand('copy')) {
             document.execCommand('copy');
        }
        document.body.removeChild(input);
    }
    

    相关文章

      网友评论

          本文标题:前端学习笔记--js实现复制功能

          本文链接:https://www.haomeiwen.com/subject/ngduzftx.html