本段代碼摘自微軟docs網站上,目前須要解決在IE瀏覽器中觸發copy事件的方法,也能夠直接調用jquery。javascript
<!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>