H5/純JS實現:把網頁中的文字復制到剪切板


 copy =() => {
    const dom = document.getElementById(`collect-text-${t.Id}`)
    const selection = window.getSelection()
    const range = document.createRange()

    if (!dom || !selection || !range) return

    // 選擇復制目標
    range.selectNodeContents(dom)
    selection.removeAllRanges()
    selection.addRange(range)

    // 已復制文字
    console.log('selectedText', selection.toString())

    // 執行復制
    document.execCommand('copy')

    // 去除所有選中
    selection.removeAllRanges()
   // 復制內容成功,通過ctrl+v粘貼使用!
  }

 

參考資料:

select :  https://github.com/zenorocha/select

 

clipboard.js :  https://github.com/zenorocha/clipboard.js

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM