JavaScript实现点击复制功能

JavaScript实现点击复制功能。

原理:原生JavaScript提供了一个方法:

window.document.execCommand('copy');

这个方法就是对当前的以选中的字符进行复制,这边就又有一个问题,就是我们该怎么选中?input、textarea等标签提供了select方法,我们就可以使用这个来模拟我们用户选中。我们可以创建一个input标签,当然这个标签要是透明的,或者是不可见的,不能平白无辜在页面上多一个标签吧,然后给这标签的value值赋上我们想要复制的内容,最后我们在执行上面的select模拟选中,最后在执行execCommand(‘copy’)然后再将标签去除就可以啦。
原理很简单,这边直接上代码。

function copy(data, callback) {
  //创建input
  const input = window.document.createElement('input');
  //赋值并设置不可见
  input.setAttribute('value', data);
  input.setAttribute('display', 'none');
  document.body.appendChild(input);
  input.select();
  let err = undefined;
  //捕获异常,如果浏览器不支持则抛出异常。
  try {
    const status = window.document.execCommand('copy');
    if (status) {
      callback(err, data);
      return;
    }
    callback(new Error('复制失败'), data);
  } catch (error) {
    err = error;
    callback(err, data);
  } finally {
    window.document.body.removeChild(input);
  }
}
案例
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button onclick="COPY()">复制</button>
</body>
</html>
<script src="./copyText.js"></script>
<script>
  function COPY() {
    copy('777', (err, data) => {
      if (!err) {
        console.log(data);
      } else {
        console.log(err.message);
      }
    })
  }
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ycopy ver 0.1 beta release 两千零十年十二月 Windows command line 文件复制工具。 在Windows 64位环境下测试通过。 本版为为初次测试版,有什么问题大家多提提。 1 文件和文件夹复制, -s=源文件/文件夹, -b=目的文件/文件夹 2 支持通配符* 3 允许设置日期间隔,帮助大家复制n天前的文件到新位置。-i=n,n=当前系统时间-源文件最后修改时间,n为正整数。 4 覆盖已存在的同名目标文件,/o 5 成功复制后删除源文件,/r 6 新建目标文件夹,/cf ---- 如果 目标文件夹不存在,复制自动放弃执行。 7 安装完成后,不会添加程序快捷方式,进入开始菜单。 Qt C++ 编写 example1: ycopy.exe -s=C:\Users\Yun Liu\D*k*\test\*Te*;-b=C:\Users\Yun Liu\Desktop\test\backup;-i=0 Copy files from different folders to one folder. example2: ycopy.exe -s=C:\Users\Yun Liu\D*k*\test\*Te*;-b=C:\Users\Yun Liu\Desktop\test\backup\*b9*;-i=100;/o Copy files frome different folders to different folders, if the file is older than 100 days. If target file exists, overwrite it. example3: ycopy.exe -s=C:\Users\Yun Liu\Desk*\test\UpdateTemp\2010source.txt;-b=C:\Users\Yun Liu\Desktop\test\backup\2010sourceTest.txt;-i=0 Copy the file to the new location and rename it right away. example4: ycopy.exe -s=C:\Users\Yun Liu\Desk*\test\*Temp\*source*.txt;-b=C:\Users\Yun Liu\Desktop\test\backup\2010source.txt;-i=0;/o Only works correct, when only one file was found according to the -s argument.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值