纯js 文本复制功能

388 阅读1分钟

最近在项目中需要点击复制的功能,然后百度看了一下网上的各种方法,有引用插件的(不太理想,一个功能就引用一个插件,代码太冗余了),有自己封装的(可能技术发展比较快,有些都失效了),但是根据他们的介绍,自己找到相关的API,总结了一下,适用于Chrome Firefox (Gecko) Internet Explorer(9+) Opera Safari

方法一:使用Selection和Range对象

第一步

创建一个Range对象

let range = document.createRange()
// 传入需要选中的元素节点
range.selectNodeContents(Node节点)

创建一个Selection对象

var selection = document.getSelection()
// 清空选中的区域
selection.removeAllRanges()
// 添加选中区域
selection.addRange(range)

调用复制

document.execCommand('Copy')

Code

function copyHandler(node){
    let range = document.createRange()
    range.selectNodeContents(node)
    let selection = document.getSelection()
    selection.removeAllRanges()
    selection.addRange(range)
    document.execCommand('Copy')
}

方法二:使用input和textarea元素的select()方法

弊端

需要创建多余的标签,而且input和textarea必须显示,设置以下任何一个样式都不起作用: display:none visibility:hidden width:0 height:0

还是直接上代码看吧

html

<div class='error-correction-row'>
  <label class='talqs-label'>ID</label>
  
  <span class="question-id-main">fa020e90e7de4bd0d399ezvzvvzvz58a5fab92f7</span>
  
  <textarea class='queIdInput'
  id='queIdInput' value='fa020e90e7de4bd0d399ezvzvvzvz58a5fab92f7' />
  
  <button class='question-id-btn' id='question-id-btn'
    @click="copyHandler">复制</button>
    
</div>

css

<style>
// 这样设置就可以在点击复制的时候看不到textarea元素
.queIdInput{
    border: none;
    width: 1px;
    height:1px;
    outline: none;
    opacity: 0;
}

</style>

js

<script>

    let copyBtn=dcoument.getElementById('question-id-btn')
    
    copyBtn.addeventlistener("click",copyHandler,false)
    
    function copyHandler(){
        let queIdInput=dcoument.getElementById('queIdInput')
        
        queIdInput.select()
        document.execCommand('Copy')Ï
    }
</script>