JS實現複製到剪貼簿(支援IE和Firefox)

Web開發者發表於2011-12-24

這個複製內容到剪貼簿的功能是相容ie及火狐瀏覽器的,直接點選"複製"按鈕就可以儲存到系統剪貼簿。來自admin10000.com

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Web開發者 - www.Admin10000.com </title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript">
	function copy_clip(txt) {
        if (window.clipboardData) {
                window.clipboardData.clearData();
                window.clipboardData.setData("Text", txt);
        } else if (navigator.userAgent.indexOf("Opera") != -1) {
                window.location = txt;
        } else if (window.netscape) {
                try {
                        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                        alert("您的firefox安全限制限制您進行剪貼簿操作,請在新視窗的位址列裡輸入'about:config'然後找到'signed.applets.codebase_principal_support'設定為true'");
                        return false;
                }
                var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
                if (!clip)
                        return;
                var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
                if (!trans)
                        return;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                var copytext = txt;
                str.data = copytext;
                trans.setTransferData("text/unicode", str, copytext.length * 2);
                var clipid = Components.interfaces.nsIClipboard;
                if (!clip)
                        return false;
                clip.setData(trans, null, clipid.kGlobalClipboard);
        }
	}
	</script>
</head>
<body>
<input type="text" id="txt" value="www.Admin10000.com" /> 
<button onclick="copy_clip(document.getElementById('txt').value);alert('恭喜,複製成功!');">複製內容</button> 
</body>
</html>

相關文件:JS複製內容到剪貼簿(相容IE/FF/Chrome/Safari所有瀏覽器)

相關文章