• JS 方法实现复制粘贴


    背景

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

    • 创建一个 textarea 标签

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

    • 给这个 textarea 赋值

    • 把这个 textarea 塞到页面中

    • 调用 textarea 的 select 方法

    • 调用 document.execCommand('copy')

    • 删除 textarea 标签

    代码如下

    1. const legacyCopy = (value: string) => {
    2. const ta = document.createElement('textarea');
    3. ta.value = value ?? '';
    4. ta.style.position = 'absolute';
    5. ta.style.opacity = '0';
    6. document.body.appendChild(ta);
    7. ta.select();
    8. document.execCommand('copy');
    9. ta.remove();
    10. };

    navigation.clipboard

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

    writeText

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

    1. <body>
    2. <div>
    3. <button id="btn">复制button>
    4. <input id="input" />
    5. div>
    6. <script>
    7. const btn = document.getElementById('btn')
    8. const input = document.getElementById('input')
    9. let value = ''
    10. btn.onclick = async () => {
    11. await navigator.clipboard.writeText(value);
    12. }
    13. input.oninput = (e) => {
    14. value = e.target.value
    15. }
    16. script>
    17. body>

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

    readText

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

    1. <body>
    2. <div>
    3. <button id="copy">复制button>
    4. <input id="input" />
    5. div>
    6. <div>
    7. <button id="paste">粘贴button>
    8. <span id="span">span>
    9. div>
    10. <script>
    11. const copy = document.getElementById('copy')
    12. const paste = document.getElementById('paste')
    13. const input = document.getElementById('input')
    14. const span = document.getElementById('span')
    15. let value = ''
    16. copy.onclick = async () => {
    17. await navigator.clipboard.writeText(value);
    18. }
    19. paste.onclick = async () => {
    20. span.innerHTML = await navigator.clipboard.readText()
    21. }
    22. input.oninput = (e) => {
    23. value = e.target.value
    24. }
    25. script>
    26. body>

  • 相关阅读:
    猿创征文 |【算法入门必刷】数据结构-栈(五)
    TCC丢包率计算
    基于DBC Signal Group生成Autosar SR接口(2)
    Flink处理函数(一)
    华为Hcia-数通学习(更改策略)
    js回调函数
    ES6-新增方法
    爆款视频怎么做?这里或许有答案
    盘点年度最佳10大顶级绘图软件,满足你99%的图表需求,赶紧收藏
    【Python编程】教你如何打造极致体验的五子棋对战游戏
  • 原文地址:https://blog.csdn.net/aGreetSmile/article/details/132700556