如何使用JavaScript将文本内容复制到剪贴板中
在网上找了几篇关于JS将自定义文本添加到剪切板的文章,很多都无法使用,后来找到了一段代码,将一段文件添加到剪切板的功能挺好用的,现在附下,供大家下载使用。
在网上找了几篇关于JS将自定义文本添加到剪切板的文章,很多都无法使用,后来找到了一段代码,将一段文件添加到剪切板的功能挺好用的,现在附下,供大家下载使用。
function CopyToClipboard (input) {
var textToClipboard = input;
var success = true;
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData ("Text", textToClipboard);
}
else {
// create a temporary element for the execCommand method
var forExecElement = CreateElementForExecCommand (textToClipboard);
/* Select the contents of the element
(the execCommand for 'copy' method works on the selection) */
SelectContent (forExecElement);
var supported = true;
// UniversalXPConnect privilege is required for clipboard access in Firefox
try {
if (window.netscape && netscape.security) {
netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
}
// Copy the selected content to the clipboard
// Works in Firefox and in Safari before version 5
success = document.execCommand ("copy", false, null);
}
catch (e) {
success = false;
}
// remove the temporary element
document.body.removeChild (forExecElement);
}
return success;
}
function CreateElementForExecCommand (textToClipboard) {
var forExecElement = document.createElement ("div");
// place outside the visible area
forExecElement.style.position = "absolute";
forExecElement.style.left = "-10000px";
forExecElement.style.top = "-10000px";
// write the necessary text into the element and append to the document
forExecElement.textContent = textToClipboard;
document.body.appendChild (forExecElement);
// the contentEditable mode is necessary for the execCommand method in Firefox
forExecElement.contentEditable = true;
return forExecElement;
}
function SelectContent (element) {
// first create a range
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (element);
// select the contents
var selection = window.getSelection ();
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
}
版权声明:
本站资源和文章内容大部分收集于网络,
本站所有资源的版权均属于原作者所有,
本站资源只用于参考学习,请勿直接商用,
若由于商用引起版权纠纷,一切责任均由使用者承担。
若有侵权之处请联系站长我们会第一时间删除
本文由XM技术学习分享发布,如需转载请注明出处。