js 复制div文本

实现的效果如下图所示:(注:图是第三种方法)

复制完成后就直接ctrl+v粘贴就行了: 

1. 第一种方法 ,运用隐藏textarea来实现复制

    <div style="padding-bottom:10px"  id="copyId">
        水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水 
        水水水水水水水水水水水水水水水水水水水水水水水水水
    </div>
    <textarea id="input" ></textarea>
    <button type="button" (click)="copy()"></button>

  ts中的执行方法是:

  copy(){
    var text = document.getElementById("copyId").innerText;
    var input = document.getElementById("input");
    input.textContent = text; // 修改文本框的内容
    input.select(); // 选中文本
    document.execCommand("copy"); // 执行浏览器复制命令
  }

   css的设置为: 

#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}

2.  第二种办法:虚拟一个新建一个div

   

var oInput = document.createElement('input');
    oInput.value = "sssssssssssss";
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    oInput.className = 'oInput';
    oInput.style.display = 'none';

3. 第三种方法,windows选中的方法

    <div style="padding-bottom:10px"  id="copyId">
        水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水 
        水水水水水水水水水水水水水水水水水水水水水水水水水
    </div>
    <button type="button" (click)="copy()"></button>

ts的执行方法是:

  copy() {
    var val = document.getElementById('copyId');
    window.getSelection().selectAllChildren(val);
    document.execCommand("Copy");
  }

本文参考文献:1. 原生 js 实现点击按钮复制文本 - Wise.Wrong - 博客园

                         2. js复制隐藏域中的文字 -  - 博客园

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wu_223

嘿嘿,求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值