原生JS實現粘貼到剪貼板

本文主要討論原生方法git

目前常見的實現粘貼到剪貼板主要有如下兩種方法:github

  • 第三方庫 clipboard
  • 原生JS, 主要是 document.execCommand方法

第一種方法按照文檔說明,設置觸發元素的data-clipboard-text 或者 data-clipboard-target便可,不作說明,詳見文檔設計模式

第二種方法:
document.execCommand瀏覽器

這個方法的兼容性其實不算很好,特別是移動端,具體這裏有, 但clipboard針對部分機型也有問題,因此具體使用仍是得看狀況, 使用該方法前要先看瀏覽器是否支持bool = document.execCommand('copy')app

MDN對上述方法的解釋以下:設計

當一個HTML文檔切換到 設計模式 designMode時,文檔對象暴露 execCommand 方法,該方法容許運行命令來操縱 可編輯區域的內容。

注意加粗部分,設計模式 ,即:使用前咱們需切換文檔模式爲設計模式code

document.designMode = 'on'

完成運行命令以後再設置值爲off
還有個加粗部分,可編輯區域 ,默認的input和textarea元素是可編輯(設置一個元素的contenteditable="true"也可激活元素的編輯模式)對象

先來看錶單元素如何實現ip

ele.addEventListener('click', () => {
    document.designMode = 'on'
    let bool = document.execCommand('copy')
    if (!bool) {
        alert('sorry, 手動複製吧')
    } else {
        let val = 'something'
        let inputEle = document.createElement('input')
        document.body.appendChild(inputEle)
        inputEle.setAttribute('value', val)
        inputEle.setAttribute('readonly', 'readonly')
        inputEle.select()
        document.execCommand('copy')
        document.body.removeChild(inputEle)
        alert('copied')
    }
    document.designMode = 'off'
})

爲避免出現光標或者拉起輸入法,須要給元素設置readonly屬性rem

inputEle.select()方法在一些瀏覽器中有時不能選中全部內容,這時須要利用inputeElement的setSelectionRange方法:

HTMLInputElement.setSelectionRange 方法能夠從一個被 focused 的 <input>
元素中選中特定範圍的內容。

綜上加兩行:

...
inputEle.focus()
inputEle.setSelectionRange(0, inputEle.value.length)
document.execCommand('copy')
...

若是不是input等表單元素,不能使用selectsetSelectRange的話,那麼咱們能夠使用getSelectioncreateRange方法來模擬這個過程了,Selection對象表示用戶選擇的文本範圍或光標的當前位置,知足執行execComman命令的可編輯活動區域,以下

let range = document.createRange()
let tar = document.querySelector('#code')
range.selectNodeContents(tar)
let selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
document.execCommand('copy')
selection.removeAllRanges()

上述針對非input,textarea等表單元素也能實現了

相關文章
相關標籤/搜索