1分钟学会 2 个复制文本到剪贴板的方法

前端达人

共 1291字,需浏览 3分钟

 ·

2021-10-30 11:17

虽然用户自己可以选择文本进行内容的复制到剪贴板,但是有一些场景,我们需要通过一个按钮事件进行当前文本区域内容的复制,这个场景在日常中的需求还是比较常见的,你会怎么做呢?

一、大多人都在用的方法

你可能在用这个方法进行剪贴板的复制

  • 创建一个文本框区域 textarea
  • 然后将你希望复制的内容填充此文本框
  • 接下来将文本框添加至页面
  • 然后使用 select 方法进行文本框内容的选择
  • 然后执行 copy 命令
  • 最后移除 textarea 文本框

基于以上说明,示例代码如下:

function copyToClipboard(text){
    const textArea = document.createElement("textarea")
    textArea.value = text

    document.body.appendChild(textArea)

    textArea.focus()
    textArea.select()

    document.execCommand('copy')

    document.body.removeChild(textArea)
}

二、你可能不知道的新方法

你可以使用浏览器的新API——navigator.clipboard,一段代码就能实现简单的内容复制

function copyToClipboard(text){
    navigator.clipboard.writeText(text)
}

三、将两个方法整合一起

现在我们可以将新旧方法合在一起,避免新方法在旧的浏览器不能使用,我们需要进行浏览器兼容的适配,示例代码如下:

function copyToClipboard(text){
    if(navigator.clipboard){
        navigator.clipboard.writeText(text)
        return //codes below wont be executed
    }
    const textArea = document.createElement("textarea")
    textArea.value = text

    document.body.appendChild(textArea)

    textArea.focus()
    textArea.select()

    document.execCommand('copy')

    document.body.removeChild(textArea)
}

今天的文章就分享到这里,感谢你的阅读。

来源 

网址:https://dev.to/0shuvo0/copy-text-to-clipboard-in-jstwo-ways-1pn1

作者:Shuvo

浏览 64
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报