前端如何实现复制功能

话不多说直接上代码:



function copyToClipboard(elem) {

            var targetId = "_hiddenCopyText_";

            var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";

            var origSelectionStart, origSelectionEnd;

            if (isInput) {

                // 如果是input标签或textarea,则直接指定该节点

                target = elem;

                origSelectionStart = elem.selectionStart;


                origSelectionEnd = elem.selectionEnd;

                console.dir( elem)

                console.log(  elem.selectionEnd)

            } else {

                // 如果不是,则使用节点的textContent

                target = document.getElementById(targetId);

                if (!target) {

                    //如果不存在,则创建一个

                    var target = document.createElement("textarea");

                    target.style.position = "absolute";

                    target.style.left = "-9999px";

                    target.style.top = "0";

                    target.id = targetId;

                    document.body.appendChild(target);

                }

                target.textContent = elem.textContent;

            }

            // 聚焦目标节点,选中它的内容

            var currentFocus = document.activeElement;


            target.focus();

            target.setSelectionRange(0, target.value.length);

            // 进行复制操作

            var succeed;

            try {

                succeed = document.execCommand("copy");

            } catch(e) {

                succeed = false;

            }

            // 不再聚焦

            if (currentFocus && typeof currentFocus.focus === "function") {

                currentFocus.focus();

            }

            if (isInput) {

                // 清空临时数据

                elem.setSelectionRange(0, 0);

            } else {

                // 清空临时数据

                target.textContent = "";

            }

            return succeed;

        }

        $("#copy").on('click',function(){

        var copytxt=document.querySelector('#copyTxt');

            copyToClipboard(copytxt);

        });


tag:前端实现复制功能主要的API有:

input : selectionStart , slectionEnd ,setSelectionRange 

document :  execCommand;
思路如下:

将我们想要复制的内容用 input.setSelectionRange( num, num ) 进行选择: 之后再用document.exeCommand('copy') ;方法进行复制 !

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。