HTML:
- <body>
- <form id="form1" runat="server">
- <div>
- <textarea id="txtArea" cols="30" rows="3">我是一个文本,Hello World!</textarea><br />
- <input type="button" name="name" value="复制内容" onclick="copyToClipBoard('txtArea')" />
- </div>
- </form>
- </body>
JS:
- <script type="text/javascript">
- //复制文本框
- function copyToClipBoard(id) {
- var code = $("#" + id).val();
- code = HTMLDeCode(code);
- var tip = copyCode(code);
- if (tip == 0) { //0 成功 1 失败 2 不支持 3 已经提示
- var _open = tool.getCookieValue("open");
- if (_open == "0" && _global.security == "1") {
- alert("您当前的安全级别为高,此时“完全公开”代码将无效\n若要继续选择“完全公开”代码,请将安全级设置为“中”。");
- } else {
- tool.setCenter($("#box2"), 0);
- $("#box2").fadeIn();
- }
- } else if (tip == 1) {
- alert("复制失败,请重试!");
- } else if (tip == 2) {
- alert("您的浏览器不支持此功能");
- }
- if (typeof pgvSendClick == "function") {
- if (tool.getCookieValue("open") == 1) {
- pgvSendClick({ hottag: 'R1JT.wp.index.security' });
- } else {
- pgvSendClick({ hottag: 'R1JT.wp.index.open' });
- }
- }
- }
- //去掉特殊符号
- function HTMLDeCode(str) {
- var s = "";
- if (str.length == 0) return "";
- s = str.replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/ /g, " ")
- .replace(/'/g, "'")
- .replace(/"/g, "\"");
- return s;
- }
- //执行复制
- function copyCode(txt) { //0 成功 1 失败 2 不支持 3 已经提示
- if (window.clipboardData) { //IE
- window.clipboardData.clearData();
- window.clipboardData.setData("Text", txt);
- return 0;
- } else if (navigator.userAgent.indexOf("Opera") != -1) { //Opera
- return 2;
- } else if (window.netscape) { //火狐
- try {
- netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
- } catch (e) {
- alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
- return 3;
- }
- var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
- if (!clip)
- return 1;
- var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
- if (!trans)
- return 1;
- 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 1;
- clip.setData(trans, null, clipid.kGlobalClipboard);
- return 0;
- } else { //chrome ,safra
- return 2;
- }
- }
- </script>