JS将字符串变量(页面链接)复制到剪贴板

本文详细介绍了如何在JavaScript中使用`document.execCommand(copy)`方法实现内容复制,包括创建input元素、设置值、选择内容并检测浏览器兼容性。
摘要由CSDN通过智能技术生成

借用input框来使用document.execCommand(‘copy’)方法

//手动创建一个input框
const input = document.createElement('input');
    document.body.appendChild(input);
    //将想要复制的内容设置为input框的内容
    input.setAttribute('value', window.location.href);
    //选中input框的内容
    input.select();
    //判断当前浏览器是否支持该复制方法
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        console.log('复制成功');
        ElMessage({
            message:'内部链接复制成功,您可以通过粘贴分享给其他人',
            type:'success',
            showClose:true
        })
    }else{
        console.log('失败')
        ElMessage.error('复制失败!当前浏览器不支持复制')
    }
    //移除input节点
document.body.removeChild(input);

document.exceCommand()方法教程:
详解Javascript中document.execCommand()的用法以及指令参数列表

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值