js实现copy

  在js中实现copy。看似很简单的功能。实际上却有点复杂。因为只有能select的元素或者contentEditable的元素才支持document.execCommand('copy'),所以经过百度之后发现了

range这么个属性

 function copy(copyEle) {
        if (copyEle.nodeName.toLowerCase() === "input") {
            copyEle.select();
            document.execCommand('copy');
        } else {
            var range = document.createRange();
            var selection = window.getSelection();
            range.selectNode(document.getElementById('href'));
            if (selection.rangeCount > 0) selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            selection.removeAllRanges();
        }

    }
    document.querySelector("#copy").addEventListener("click", function() {
        var copyElement = document.querySelector("#href");
        copy(copyElement);
    }, false);

目前不支持安卓

posted @ 2017-09-28 10:33  于啊  阅读(484)  评论(0)    收藏  举报