• 前端复制功能(几种形式)


    前端复制到剪贴板

    • 有时候我们点击按钮,要将一些内容复制到剪贴板,大家是怎么实现的呢?

    • 针对3种情况 , 实现点击按钮实现复制到剪贴板 👇

    Ⅰ、点击,复制一个 input 框

    • 表单元素是可以直接被选中的,我们直接 select 选中
    <body>
      <input type="text" value="123456" id="textInput">
      <button onclick="copyInput()">copybutton>
    body>
    <script>
    function copyInput() {
        const input = document.getElementById("textInput");
        input.select();  //选中该输入框
        document.execCommand('copy');  //复制该文本 
    }
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 👉 选中该元素
    • 👉 复制选中的内容

    Ⅱ、点击,复制一个值

    • 则需要个载体 ,我们先创建它,复制完成在删除
    <body>
        <button onclick="copy(123456)">Copybutton>
    body>
    <script>
    function copy(val) {
        const input = document.createElement("input"); //创建input 
        input.setAttribute("value", val);            //把input设置value
        document.body.appendChild(input);            //添加这个dom对象
        input.select();                              //选中该输入框
        document.execCommand("copy");                //复制该文本 
        document.body.removeChild(input);            //移除输入框
    }
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 单纯复制一个值,实际上还是得选中一个元素
    • 👉 创建 input
    • 👉 设置其值
    • 👉 在dom 中添加该元素
    • 👉 选中该元素
    • 👉 复制选中的内容
    • 👉 移除 input

    Ⅲ、点击,复制一个 dom 中的内容

    非表单元素, 我们没办法选中,所以需要其他方法

    <body>
        <div id="box">123456div>
        <button onclick="copyDiv()">button>
    body>
    <script>
        function copyDiv() {
            var range = document.createRange();
            range.selectNode(document.getElementById('box'));
            var selection = window.getSelection();
            if (selection.rangeCount > 0) selection.removeAllRanges();
            selection.addRange(range);
            return document.execCommand('copy');
        }
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 👉 通过 createRange 返回 range 对象
    • 👉 通过 range 的 selectNode 方法 选中 该 dom 的边界
    • 👉 创建 selection 通过 addRange 去添加范围
    • 👉 如果之前有则清空,然后添加这个range范围
    • 👉 复制这个选中的范围
  • 相关阅读:
    LVDS转MIPIDSI/CSI-2芯片龙讯LT8918L资料分享、
    日常事务管理软件哪个好?“的修”平台如何提升工作效率?
    【luogu CF618G】Combining Slimes(矩阵乘法)(DP)
    openjudge 1.12.8 Vigenere密码
    深度讲解React Props
    《天道》中最智慧的4句话,看懂改变一生
    zookeeper配置文件
    webpack打包ts的配置及踩坑
    Deep Reinforcement Learning with Double Q-learning(double DQN)
    Spring的BeanDefinition的作用和使用方法
  • 原文地址:https://blog.csdn.net/weixin_42232622/article/details/127795040