DIV CSS 佈局教程網

一鍵複製與剪下:JavaScript 文字方塊按鈕實作
編輯:JavaScript綜合知識     

「複製到剪貼簿」這個按鈕看起來平凡,卻能省掉使用者反覆選取、按右鍵的動作。核心只有一句 execCommand。

三個函式各司其職

copy() 與 cut() 的流程幾乎一樣:先找到目標元素、選取它、建立文字範圍,然後執行剪貼簿指令。差別只在指令名稱是 Copy 還是 Cut。

function copy(ob){
  var obj = findObj(ob);
  if (obj) {
    obj.select();
    js = obj.createTextRange();
    js.execCommand("Copy");
  }
}
function cut(ob){
  var obj = findObj(ob);
  if (obj) {
    obj.select();
    js = obj.createTextRange();
    js.execCommand("Cut");
  }
}

而 findObj() 是一段兼容層,用來在各種 DOM 環境下撈到元素:

function findObj(n, d) {
  var p, i, x;
  if (!d) d = document;
  if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
    d = parent.frames[n.substring(p + 1)].document;
    n = n.substring(0, p);
  }
  if (!(x = d[n]) && d.all) x = d.all[n];
  for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
  for (i = 0; !x && d.layers && i < d.layers.length; i++)
    x = findObj(n, d.layers[i].document);
  if (!x && document.getElementById) x = document.getElementById(n);
  return x;
}

它依序嘗試框架、命名元素、document.all、表單集合、Netscape 的 layers,最後才落到標準的 getElementById——典型的 Web 大戰時代產物。

掛上按鈕

<input type="button" value="複製到剪貼簿" onClick="copy('txtOutput')">
<input type="button" value="剪下到剪貼簿" onClick="cut('txtOutput')">

<form name="fom1" method="post" action="">
  <textarea name="txtOutput" rows="5" cols="50"></textarea>
</form>

現代觀點提醒

document.execCommand 已被標記為不建議使用,新版瀏覽器要求使用者手勢授權,且在部分環境會直接失敗。新專案請改用非同步的 navigator.clipboard.writeText(),並記得包在 try/catch 裡處理權限被拒的情況。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved