zoukankan      html  css  js  c++  java
  • 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(/PS 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>
    
    
  • 相关阅读:
    石头的用途
    [转] Analysis: Khronos and OpenGL ARB merge
    ★○值得你我珍藏一世的80句话○★
    PasswordStrength 控件
    NumericUpDownExtender 控件
    ReorderList控件
    Nobot控件拒绝机器人行为
    PopupControlExtender控件
    PagingBulletedList 控件学习
    MutuallyExlcusiveCheckBox控件
  • 原文地址:https://www.cnblogs.com/grj1046/p/6726604.html
Copyright © 2011-2022 走看看