• 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>

  • 相关阅读:
    数据治理-数据仓库环境
    基于SSM架构的新闻管理系统设计与实现论文
    GDB
    MarkdownQuote:简化 Markdown 中的代码引用!
    网络工程师知识点2
    C++指针解读(5)-- 指针和数组(多维数组)
    stm32f407栈溢出导致跑程序异常
    Vscode编辑器保存时一直提示正在保存“index.vue”: 正在从“‘Vetur‘, ‘ESLint‘”获取代码操作
    【ACWing 算法基础】模拟散列表
    注塑模具外观设计有哪些特点?
  • 原文地址:https://blog.csdn.net/aGreetSmile/article/details/132700556