前端代码实现一键复制


前言

使用前端代码来一键复制文本的多种方法。


一、clipboard依赖包

用于复制和剪切文本。

使用步骤

代码如下(示例):npm i clipboard

function clickBtnHandle(){
        const clipboard = new Clipboard('#copy')
        clipboard.on('success',e=>{
                Message.success('成功复制到剪切板')        //Message引用的是element组件的
                clipboard.destory()
        })
        clipboard.on('err',e=>{
                Message.error('链接复制失败,该浏览器不支持复制!')
                clipboard.destory()
        })
}

二、 复制二维码

使用步骤

<img id='wxCode' :src='qrCodeUrl' alt=""> 
copyCode(){
        const testImg = document.querySelector("#wxCode");
        const selection = window.getSelection();
        //清除选中的
        if(selection.rangeCount>0) selection.removeAllRanges();
        if(!document.queryCommandSupported('copy')){
                return Message.error('浏览器暂不支持复制命令');
        }
        const range = document.createRange()
        range.selectNode(testImg);
        selection.addRange(range);
        document.execCommand("copy");
        selection.removeAllRanges();
        Message.success('二维码复制成功!')
}

三、复制文本内容

使用步骤


<button onClick='copyHandle'>点击复制</button>

<textarea id="copy">copy的数据</textarea>

copyHandle(e){

        const text = document.getElementById('ipt').innerText

        const input = docment.getElementById('copy')

        input.value = text

        input.select() //选中文本

        document.execCommand('copy');

}

总结

以上三种就是常见的自定义复制的方式。

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值