美文网首页
前端如何实现复制功能

前端如何实现复制功能

作者: 小李子_前端 | 来源:发表于2018-01-29 10:35 被阅读0次

话不多说直接上代码:


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') ;方法进行复制 !

相关文章

网友评论

      本文标题:前端如何实现复制功能

      本文链接:https://www.haomeiwen.com/subject/dnxxzxtx.html