利用JS實現複製/貼上功能

weixin_34041003發表於2012-01-11

1、最基本的複製

  Java程式碼

  <script language="javascript">

  function readTxt()

  {

  alert(window.clipboardData.getData("text"));

  }

  function setTxt()

  {

  var t=document.getElementById("txt");

  t.select();

  window.clipboardData.setData('text',t.createTextRange().text);

  }

  </script>

  <input name="txt" value="測試">

  <input type="button" value="複製" onclick="setTxt()">

  <input type="button" value="讀取" onclick="readTxt()">

  2、擴充套件複製:複製表格

  Java程式碼

  <INPUT TYPE="button" value="選中測試表格" onclick="CopyTable()">

  測試

  <TABLE border="1" id="oTable">

  <TR>

  <TD>測試表格</TD>

  <TD>測試表格</TD>

  </TR>

  <TR>

  <TD>測試表格</TD>

  <TD>測試表格</TD>

  </TR>

  </TABLE>文字

  <SCRIPT LANGUAGE="JavaScript">

  <!--

  function CopyTable()

  {

  var txt = document.body.createTextRange();

  txt.moveToElementText(document.getElementById('oTable'));

  txt.select();

  }

  //-->

  </SCRIPT>

  、相容IE,firefox等瀏覽器的複製

  Java程式碼

  <script>

  function copyToClipboard(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("被瀏覽器拒絕!\n請在瀏覽器位址列輸入'about:config'並回車\n然後將'signed.applets.codebase_principal_support'設定為'true'");

  }

  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>

  <button onclick="copyToClipboard('你好!');">複製文字“你好!”</button>

  <textarea id="test"></textarea>

相關文章