话不多说 上代码
在按钮函数里面填CopyToClipboard ("这里填复制文本内容 ");
就实现复制了
function CopyToClipboard (input) {
var textToClipboard = input; //文本到剪贴板
var success = true;
if (window.clipboardData) { // 浏览器
window.clipboardData.setData ("Text", textToClipboard);
}
else {
var forExecElement = CreateElementForExecCommand (textToClipboard);
SelectContent (forExecElement);
try {
if (window.netscape && netscape.security) {
netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
}
//将选定内容复制到剪贴板
success = document.execCommand ("copy", false, null);
}
catch (e) {
success = false;
}
//移除临时元素
document.body.removeChild (forExecElement);
}
}
function CreateElementForExecCommand (textToClipboard) {
var forExecElement = document.createElement (“div”);
//在可见区域以外
forExecElement.style.position = “absolute”;
forExecElement.style.left = “-10000px”;
forExecElement.style.top = “-10000px”;
//将必需的文本写入元素并追加到文档中
forExecElement.textContent = textToClipboard;
document.body.appendChild (forExecElement);
//内容编辑模式在火狐的exec命令方法是必要的
forExecElement.contentEditable = true;
return forExecElement;
}
function SelectContent (element) {
//创建一个范围
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (element);
//选择内容
var selection = window.getSelection ();
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
}