純js 文本複製功能

最近在項目中須要點擊複製的功能,而後百度看了一下網上的各類方法,有引用插件的(不太理想,一個功能就引用一個插件,代碼太冗餘了),有本身封裝的(可能技術發展比較快,有些都失效了),可是根據他們的介紹,本身找到相關的API,總結了一下,適用於Chrome Firefox (Gecko) Internet Explorer(9+) Opera Safaricss

方法一:使用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必須顯示,設置如下任何一個樣式都不起做用:html

display:none
visibility:hidden
width:0
height:0

仍是直接上代碼看吧node

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>
相關文章
相關標籤/搜索