h5页面,文本复制功能总结

  <div>
        <span id="user_ref_id">123123123123123</span>
        <input style="margin-left: 30px;" type="button" onclick="cp(document.getElementById('user_ref_id'));"
            value="复制给好友">
        <input type="text">
    </div>

第一种方法,在较旧的浏览器(如 IE)和现代浏览器(如 Chrome、Firefox、Safari)中都有一定的兼容性

 function selectText(x) {
            if (document.selection) {
                var range = document.body.createTextRange();
                range.moveToElementText(x);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();
                var range = document.createRange();
                selection.removeAllRanges();
                range.selectNodeContents(x);
                selection.addRange(range);
            }
        }
        function cp(x) {
            selectText(x);
            document.execCommand("copy");
            alert("复制成功,快去分享好友吧")
        }

第二种方法,使用的Clipboard API 来进行剪切、复制等操作。Clipboard API 提供了更强大和现代的方式来操作剪贴板,并且在大多数现代浏览器中得到了广泛支持。

 function selectText(x) {
            if (document.selection) { // 兼容 IE
                var range = document.body.createTextRange();
                range.moveToElementText(x);
                range.select();
            } else if (window.getSelection) { // 兼容现代浏览器
                var selection = window.getSelection();
                var range = document.createRange();
                selection.removeAllRanges();
                range.selectNodeContents(x);
                selection.addRange(range);
            }
        }

        function cp(x) {
            selectText(x);
            if (navigator.clipboard) { // 使用 Clipboard API
                navigator.clipboard.writeText(x.innerText || x.textContent)  // 将元素的文本复制到剪贴板
                    .then(function () {
                        alert("复制成功,快去分享给好友吧");
                    })
                    .catch(function (err) {
                        alert("复制失败: " + err);
                    });
            } else {
                document.execCommand("copy");  // 退回到旧的方式(仅支持较老的浏览器)
                alert("复制成功,快去分享给好友吧");
            }
        }

推荐使用第二种方法,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值