如下所示,一個最基本的複製功能只要三行:
<script type="text/JavaScript">
function jsCopy(){
var e=document.getElementById("contents"); // 對象是 contents
e.select(); // 選擇對象
document.execCommand("Copy"); // 執行瀏覽器複製命令
}
</script>
<textarea id="contents" cols="40" rows="5"></textarea>
<br />
<input type="button" onClick="jsCopy();" value="複製" />
document.getElementById("contents") 這句話就是取得 id 為 contents 的 textarea。e.select()document.execCommand("Copy")document.execCommand(sCommand[, 交互方式, 動態參數])
三個參數分別是指令名稱、是否顯示互動介面、以及傳給指令的動態值。多數情境下後兩個參數都可以省略。
除了複製,execCommand 其實還能操作不少編輯行為:
// 相當於單擊文件中的打開按鈕
document.execCommand("Open");
// 將當前頁面另存為
document.execCommand("SaveAs");
// 剪貼選中的文字到剪貼板
document.execCommand("Cut","false",null);
// 刪除選中的文字
document.execCommand("Delete","false",null);
// 改變選中區域的字體
document.execCommand("FontName","false",sFontName);
// 改變選中區域的字體大小
document.execCommand("FontSize","false",sSize|iSize);
// 設置前景顏色
document.execCommand("ForeColor","false",sColor);
// 使絕對定位的對象可直接拖動
document.execCommand("2D-Position","false","true");
// 使對象定位變成絕對定位
document.execCommand("AbsolutePosition","false","true");
// 設置背景顏色
document.execCommand("BackColor","false",sColor);
// 使選中區域的文字加粗
document.execCommand("Bold","false",null);
// 複製選中的文字到剪貼板
document.execCommand("Copy","false",null);
// 設置指定錨點為書籤
document.execCommand("CreateBookmark","false",sAnchorName);
// 將選中文本變成超連接,若第二個參數為 true 會出現參數設置對話框
document.execCommand("CreateLink","false",sLinkURL);
// 設置當前塊的標籤名
document.execCommand("FormatBlock","false",sTagName);
需要說明的是,document.execCommand 已被標示為不建議使用(deprecated),FireFox 對其中部分指令本來就不支援,各家瀏覽器的實作也不一致。它之所以還能運作,主要是為了相容性而保留。
新專案建議改用非同步的 Clipboard API:
navigator.clipboard.writeText('要複製的文字')
.then(() => console.log('複製成功'))
.catch(err => console.error('複製失敗', err));
它不需要 select 文字框、也不會把焦點搶走,並可用 navigator.clipboard.readText() 反向讀取(需使用者授權)。唯一限制是必須在 HTTPS 或 localhost 環境下才能使用,因此實務上常見的做法是「優先用 Clipboard API,失敗時退回 execCommand」。