JS 方法实现复制粘贴

背景

以前我们一涉及到复制粘贴功能,实现思路一般都是:

  • 创建一个 textarea 标签

  • 让这个 textarea 不可见(定位)

  • 给这个 textarea 赋值

  • 把这个 textarea 塞到页面中

  • 调用 textarea 的 select 方法

  • 调用 document.execCommand('copy')

  • 删除 textarea 标签

代码如下

const legacyCopy = (value: string) => {
    const ta = document.createElement('textarea');
    ta.value = value ?? '';
    ta.style.position = 'absolute';
    ta.style.opacity = '0';
    document.body.appendChild(ta);
    ta.select();
    document.execCommand('copy');
    ta.remove();
  };

navigation.clipboard

上面说的是以前的方式,前几天在看 vueuse 源码的时候,发现了一个复制粘贴的 api,是 navigation 上的 clipboard

writeText

navigation.clipboard.writeText 是一个异步方法,用来将特定的值复制起来,方便你去别的地方粘贴,具体的用法如下

<body>
  <div>
    <button id="btn">复制</button>
    <input id="input" />
  </div>
  <script>
    const btn = document.getElementById('btn')
    const input = document.getElementById('input')
    let value = ''

    btn.onclick = async () => {
      await navigator.clipboard.writeText(value);
    }
    input.oninput = (e) => {
      value = e.target.value
    }
  </script>
</body>

就能实现复制,并且可以 ctrl + v 进行粘贴

readText

navigation.clipboard.writeText 是一个异步方法,用来粘贴你刚刚复制的值

<body>
  <div>
    <button id="copy">复制</button>
    <input id="input" />
  </div>
  <div>
    <button id="paste">粘贴</button>
    <span id="span"></span>
  </div>
  <script>
    const copy = document.getElementById('copy')
    const paste = document.getElementById('paste')
    const input = document.getElementById('input')
    const span = document.getElementById('span')
    let value = ''

    copy.onclick = async () => {
      await navigator.clipboard.writeText(value);
    }
    paste.onclick = async () => {
      span.innerHTML = await navigator.clipboard.readText()
    }
    input.oninput = (e) => {
      value = e.target.value
    }
  </script>
</body>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值