本段代码摘自微软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>