js使用document.execCommand实现ios,Android复制文本的功能

该博客介绍了如何在iOS和Android设备上实现一键复制当前网址链接的功能。通过获取域名和路由参数,拼接成完整网址,并利用document.execCommand方法进行复制操作。在iOS中,针对不同版本进行了兼容性处理。
摘要由CSDN通过智能技术生成
iosCopy: function () {
    window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
    var input = document.createElement("input");
    document.body.appendChild(input);
    input.setAttribute("value", 要复制的值);
    input.select();
    var range = document.createRange();
    // 选中需要复制的节点
    range.selectNode(input);
    // 执行选中元素
    window.getSelection().addRange(range);
    input.select();
    input.setSelectionRange(0, input.value.length);//适配高版本ios
    // 执行 copy 操作
    document.execCommand('copy');
    // 移除选中的元素
    window.getSelection().removeAllRanges();
    document.body.removeChild(input);
}
androidCopy: function () {
    var input = document.createElement("input");
    document.body.appendChild(input);
    input.setAttribute("value", 要复制的值);
    input.select();
    if (document.execCommand("copy")) {
        document.execCommand("copy");
    } else {
        console.log('document.execCommand用不了');
    }
    document.body.removeChild(input);
}

需求需实现一键复制当前网址链接功能,通过获取domain域名+路由参数this.props.location的pathname和search参数拼接获得当前网址,再使用document.execCommand实现复制功能

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值