【前端】js的复制功能,兼容安卓和ios,亲测有效

博客介绍了JS的复制功能,该功能可兼容安卓和IOS系统。其中,安卓系统的实现相对随意,而IOS系统识别复制需使用不能被覆盖的文本节点。最后提到可根据自身需求修整要复制的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js的复制功能,兼容安卓和ios,亲测有效

Android

安卓系统的就比较随意一点。

<script>
	var input = document.createElement('input');
    input.setAttribute('readonly', 'readonly');
    input.setAttribute('value', '我是复制的内容');
    document.body.appendChild(input);
    input.setSelectionRange(0, 9999);
    input.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        alert('复制成功');
    }
    document.body.removeChild(input);
</script>

IOS系统

IOS的用法与Android有些不同,因为IOS上识别复制得是不能被覆盖的文本节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>复制到剪切板效果</title>
</head>
<body>
<div id="copyBT">这是要复制的1内容</div>
<a id="contentas">这是复制按钮</a>
<script>
        function copyArticle(event) {
            const range = document.createRange();
            range.selectNode(document.getElementById('copyBT'));
            const selection = window.getSelection();
            if(selection.rangeCount > 0) selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            alert("复制成功")
        }
        document.getElementById('contentas').addEventListener('click', copyArticle, false);
    </script>
</body>
</html>

兼容写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>复制到剪切板效果</title>
</head>
<body>
<div id="copyBT">这是要复制的1内容</div>
<a id="contentas">这是复制按钮</a>
<script>
        function copyArticle(event) {
            if(navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)){
             const range = document.createRange();
            range.selectNode(document.getElementById('copyBT'));
            const selection = window.getSelection();
            if(selection.rangeCount > 0) selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            alert("复制成功")
            }else{
				var input = document.createElement('input');
                input.setAttribute('readonly', 'readonly');
                input.setAttribute('value','我是复制的内容');
                document.body.appendChild(input);
                input.setSelectionRange(0, 9999);
                input.select();
                if (document.execCommand('copy')) {
                    document.execCommand('copy');
                    alert('复制成功');
                }
                document.body.removeChild(input);
            }
        }
        document.getElementById('contentas').addEventListener('click', copyArticle, false);
    </script>
</body>
</html>

看懂之后,根据自己需要再去修整复制什么的数据就好了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杰肥啊

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值