javascript copy text to clipboard

本段代码摘自微软docs网站上,目前需要解决在IE浏览器中触发copy事件的方法,也可以直接调用jquery。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
</head>
<body>
    <input id="userToken" type="text" value="asdfasgihaoihhliuhlihfwie" />
    <button onclick="copyText();">Copy Text</button>
    <script type="text/javascript">
        var copyToClipboard = function (text, langClass) {
            //text = $.trim(text);

            if (langClass === 'lang-powershell') {
                text = text.replace(/\bPS C:\\>\s?/gi, '');
            }

            if (window.clipboardData && window.clipboardData.setData) {
                $(window).trigger("copy", text);
                return window.clipboardData.setData("Text", text);
            } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
                var txt = document.createElement("textarea");
                txt.textContent = text;
                txt.style.position = "fixed";
                document.body.appendChild(txt);
                txt.select();
                try {
                    return document.execCommand("copy");
                } catch (ex) {
                    return false;
                } finally {
                    document.body.removeChild(txt);
                }
            }
        }

        var copyText = function () {
            var tokenEl = document.getElementById("userToken");
            if (tokenEl) {
                var success = copyToClipboard(tokenEl.value, "");
                if (success) {
                    alert("copyed");
                }
            }
        }

    </script>
</body>
</html>

posted @ 2017-04-18 10:44  nil  阅读(397)  评论(0编辑  收藏  举报