js复制内容到剪切板

- 方法一 document.execCommand

  1. 非input / textarea中的复制
tryCopy() {
        let copyWrapper = document.querySelector(".copy-wrapper");
        // 创建select对象与range对象
        const selection = window.getSelection();
        const range = document.createRange();
        // 从当前selection对象中移除所有的range对象,
        // 取消所有的选择只 留下anchorNode 和focusNode属性并将其设置为null。
        // 这里没弄明白为什么需要先remove一下, 也没有太多资料查证 没有这句会复制失败
        if (selection.rangeCount > 0) selection.removeAllRanges();
        // 使 Range 包含某个节点的内容 使用这个 或者下面的selectNode都可以
        // range.selectNodeContents(tx)

        // 使 Range 包含某个节点及其内容
        range.selectNode(copyWrapper);
        // 向选区(Selection)中添加一个区域(Range)
        selection.addRange(range);
        // 已复制文字
        // console.log('selectedText', selection.toString())
        // 执行浏览器复制命令
        document.execCommand("copy");
      }

在这里插入图片描述

  1. 实现input / textarea中的复制
    使用input / textarea进行复制操作 这种方式更加简单 因为二者有一个select() 函数更便捷的复制而不需要去创建select对象与range对象
      let input = document.createElement('input')
      input.setAttribute('readonly', 'readonly') // 防止手机上弹出软键盘
      input.setAttribute('value', txval) // txval 为所需复制的值 变量 或者 写死
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)

但是此处注意 当你的txval为多个值拼接 并需要在剪贴板换行时 此方法无法满足,要实现换行请使用textarea

- 方法二 navigator.clipboard

使用navigator.clipboard直接执行报错 DOMException: Document is not focused,需要用户主动触发,如click中执行

const copyText = async (text) => await navigator.clipboard.writeText(text)
document.querySelector('body').addEventListener('click', () => {copyText('复制文本内容');console.log('已复制')})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值