js select 设置选中_js复制文本到粘贴板(移动端适用)

实现功能:用户点击一个按钮,系统自动复制一段文本到系统剪贴板

方案:

1.把待复制文本放入<input><textarea>类型的元素 A 中;

2.创建一个range对象并挂载 A 元素;

3.取窗口当前选中元素并清除,然后设置选中元素为第4步创建的range对象;

4.执行document.execCommand('copy')

let textarea = document.createElement('textarea');
textarea.id = "copyTextarea";
textarea.style.width = 0;
textarea.style.height = 0;
document.body.appendChild(textarea);
textarea = document.getElementById('copyTextarea');
textarea.innerHTML = text;

if(机型 == "ios"){
    const range = document.createRange();
    range.selectNode(document.getElementById('copyTextarea'));
    const selection = window.getSelection();
    if (selection.rangeCount > 0) selection.removeAllRanges();
    selection.addRange(range);
}else{
    textarea.select(); // 选中文本(select()方法对IOS部分版本无效)
}

document.execCommand('copy');
document.body.removeChild(textarea);

---文本复制成功---

注意:

  1. 通过执行el.select()也能使其获得焦点,但该方法在 Mac 下 Chrome 中有效,在 iOS 下无效(iOS某些系统版本有效)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值