js实现复制功能

博客介绍了封装方法,通过使用函数传入需要复制的内容来实现相关操作,还给出了原文地址https://www.jianshu.com/p/cc1eed9a942d 。

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

封装方法

//定义函数
            window.Clipboard = (function(window, document, navigator) {
                var textArea,
                    copy;

                // 判断是不是ios端
                function isOS() {
                    return navigator.userAgent.match(/ipad|iphone/i);
                }
                //创建文本元素
                function createTextArea(text) {
                    textArea = document.createElement('textArea');
                    textArea.innerHTML = text;
                    textArea.value = text;
                    document.body.appendChild(textArea);
                }
                //选择内容
                function selectText() {
                    var range,
                        selection;

                    if (isOS()) {
                        range = document.createRange();
                        range.selectNodeContents(textArea);
                        selection = window.getSelection();
                        selection.removeAllRanges();
                        selection.addRange(range);
                        textArea.setSelectionRange(0, 999999);
                    } else {
                        textArea.select();
                    }
                }

                //复制到剪贴板
                function copyToClipboard() {
                    try{
                        if(document.execCommand("Copy")){
                            alter('复制成功') 
                            //layer.msg('复制成功');
                        }else{
                            alter('复制失败!请手动复制!') 
                            //layer.msg('复制失败!请手动复制!');
                        }
                    }catch(err){
                            alter('复制错误!请手动复制!') 
                            //layer.msg('复制错误!请手动复制!');

                    }
                    document.body.removeChild(textArea);
                }

                copy = function(text) {
                    createTextArea(text);
                    selectText();
                    copyToClipboard();
                };

                return {
                    copy: copy
                };
            })(window, document, navigator);
           

使用函数,传人需要复制的内容

function docopy(text) {
    Clipboard.copy(text);
}

原文地址:https://www.jianshu.com/p/cc1eed9a942d

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值