js实现复制功能

一、具体场景
前端有时需要实现点击按钮复制的功能,这个时候就不能让用户去手动选择内容右键复制了。

二、实现方式
1. document.execCommand
(1)具体实现
复制时,先选中文本,然后调用document.execCommand(‘copy’),选中的文本就会进入剪贴板。这就需要借助输入框来实现对文本的选中。
具体案例:

  <button type="button" onclick="theCopy()">复制</button>
  <label style="display: block">
    <textarea id="textArea">哈哈哈哈哈哈哈哈哈111111</textarea>
  </label>
  function theCopy() {
    let textArea = document.getElementById('textArea')
    console.log(textArea);
    textArea.select()
    document.execCommand('copy')
  }

html加js这些就可以实现,但是我又发现另一种写法!!

如果内容不在输入框中,我们可以借助一个透明的输入框来实现 
 

  <button type="button" onclick="theCopy()">复制</button>
  <p id="text">哈哈哈哈哈哈哈哈哈111111</p>
  <label style="display: block">
    <textarea id="textArea" style="opacity: 0;"></textarea>
  </label>
  function theCopy() {
    let textArea = document.getElementById('textArea')
    let text = document.getElementById('text')
    textArea.innerText = text.innerHTML
    console.log(textArea);
    textArea.select()
    document.execCommand('copy')
  }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值